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