如何从格式化字符串中填充struct对象?

时间:2017-09-24 05:50:17

标签: swift string struct format

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"

使用testdata的值设置为format的最简单方法是什么? ps:格式的分隔符可以是“,”或其他。

1 个答案:

答案 0 :(得分:1)

您可以使用以下函数来获取已填充的Data对象:

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)
}

正如您在函数签名中所看到的,您可以自由添加所需的内容:

  • formattedString,例如:“yyyyMMdd;%f;%f;%f;%f;%d”。
  • dateFormat,例如:“yyyyMMdd”。
  • separator,例如:“,”或“;”。

输出:

// 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