0
struct Data {
    var DT: Date?
    var D1: Double
    var D2: Double
    var D3: Double
    var D4: Double
    var I1: Int
}

var data = [Data]()
var format = "yyyyMMdd;%f;%f;%f;%f;%d"
var test = "20170924;1.1;2.2;3.3;4.4;100"

What's the easiest way to put values from test to data using format? ps: separator in format could be "," or another.

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
Anton
  • 339
  • 5
  • 15

1 Answers1

1

You could use the following function to get a filled Data object:

func getDesiredData(formattedString: String, dateFormat: String, separator: String) -> Data? {
    let array = formattedString.components(separatedBy: separator)

    //print(array.count)

    if array.count < 6 {
        // something went wrong seprating the formatted string
        return nil
    }

    guard let d1 = Double(array[1]), let d2 = Double(array[2]), let d3 = Double(array[3]), let d4 = Double(array[4]), let i1 = Int(array[5]) else {
        // something went wrong when converting string to doubles/int
        return nil
    }

    var formatter = DateFormatter()
    formatter.dateFormat = dateFormat
    let date = formatter.date(from: array[0])

    return Data(DT: date, D1: d1, D2: d2, D3: d3, D4: d4, I1: i1)
}

As you can see in the function signature, you are free to add the desired:

  • formattedString, for example: "yyyyMMdd;%f;%f;%f;%f;%d".
  • dateFormat, for example: "yyyyMMdd".
  • separator, for example: "," or ";".

Output:

// happy case ";":
let test1 = getDesiredData(formattedString: "20170924;1.1;2.2;3.3;4.4;100", dateFormat: "yyyyMMdd", separator: ";")
dump(test1)

// happy case ",":
let test2 = getDesiredData(formattedString: "20170924,1.1,2.2,3.3,4.4,100", dateFormat: "yyyyMMdd", separator: ",")
dump(test2)

// wrong format:
let test3 = getDesiredData(formattedString: "wrong;format;goes;here", dateFormat: "yyyyMMdd", separator: ";")
dump(test3) // nil

// wrong separator:
let test4 = getDesiredData(formattedString: "20170924;1.1;2.2;3.3;4.4;100", dateFormat: "yyyyMMdd", separator: "!")
dump(test4) // nil
Ahmad F
  • 30,560
  • 17
  • 97
  • 143
  • Thanks. I know how to do this with components separatedBy and split. But is it possible in swift to make it using format? For example, var str = String(format: "yyyyMMdd;%f;%f;%f;%f;%d", data[0],... ) will give me a string using format, is it possible to do just the opposite? – Anton Sep 24 '17 at 07:25
  • Well, these questions might be related to what are asking for: https://stackoverflow.com/questions/24074479/how-to-create-a-string-with-format https://stackoverflow.com/questions/24051314/precision-string-format-specifier-in-swift but I'm not pretty sure if they would be a solution for what are you looking for... – Ahmad F Sep 24 '17 at 07:39