如何快速遍历[Dictionary <String,String>]字典数组?

时间:2019-10-03 21:00:17

标签: arrays swift string dictionary

我有一个像这样设置的字典数组:

var tableViewData: [Dictionary<String, String>] = []

如果我打印tableViewData,它看起来像这样:

[["End Time": "01:31 PM", "Date": "09-25-2019", "Duration": "23", "Start Time": "01:08 PM"], ["Start Time": "01:31 PM", "End Time": "01:54 PM", "Duration": "23", "Date": "09-25-2019"]]

我已经枚举并使用了for循环,但是我似乎无法以我想要的方式获得数据。

我曾尝试遵循其他有关堆栈溢出的问题,但我认为它们的数据设置方式与我的完全不同

How do I iterate through a [String:[String]] Dictionary in Swift

Swift for loop: for index, element in array?

我的目标是仅提取每一行的值条目,以便将其保存为CSV。

我希望它看起来像这样:

Date, Start Time, End Time, Duration    
09-25-2019, 01:08 PM, 01:31 PM, 23
09-25-2019, 01:31 PM, 01:54 PM, 23

1 个答案:

答案 0 :(得分:2)

您应该结构化数据并使其符合Codable。

Xcode 11•Swift 5.1

struct Event: Codable {
    let date, startTime, endTime, duration: String
    private enum CodingKeys: String, CodingKey {
        case date = "Date", startTime = "Start Time", endTime = "End Time", duration = "Duration"
    }
}

然后,您可以简单地创建一个只读的计算属性,以从事件集合中创建自定义字符串:

extension Collection where Element == Event {
    var csv: String {
        "Date, Start Time, End Time, Duration\n" +
        map {"\($0.date), \($0.startTime), \($0.endTime), \($0.duration)\n"}.joined()
    }
}

游乐场测试:

let tableViewData = [["End Time": "01:31 PM", "Date": "09-25-2019", "Duration": "23", "Start Time": "01:08 PM"], ["Start Time": "01:31 PM", "End Time": "01:54 PM", "Duration": "23", "Date": "09-25-2019"]]

do {
    let data = try JSONSerialization.data(withJSONObject: tableViewData)
    let events = try JSONDecoder().decode([Event].self, from: data)
    print(events.csv)
} catch {
    print(error)
}

这将打印

  

日期,开始时间,结束时间,持续时间

     

09-25-2019,01:08 PM,01:31 PM,23

     

09-25-2019,01:31 PM,01:54 PM,23