将带有分隔符的数组解析为键值

Parsing an array with separators into key-values

我正在尝试使用 Swift 5 将数组安全地解析为键值。这是一个示例 -

["BirthDate=1976-09-11", "Name=Smith", "Status=Alive"]

或者,如果在上面使用 split(separator: "=") 后有帮助,也许可以使用二维数组 -

[["BirthDate", "1976-09-11"], ["Name", "Smith"], ["Status", "Alive"]]

现在,这变成了 Array<Substring>。我想到了 Decodable 并将其转换为 ,但它并没有引导我到任何地方。

您可以使用 reduce(into:_:):

let array = ["BirthDate=1976-09-11", "Name=Smith", "Status=Alive"]

let dictionary = array.reduce(into: [String: Any]()) { (result, current) in
    let separated = current.components(separatedBy: "=")
    guard separated.count == 2 else { return }
    result[separated[0]] = separated[1]
}

输出:

$> ["Status": "Alive", "Name": "Smith", "BirthDate": "1976-09-11"]

编辑:,第一行可以写成 let dictionary = array.reduce(into: [:]) { ... },然后 dictionary 将是 [AnyHashable : Any],或者可以是 let dictionary = array.reduce(into: [String: String]()) { ... }dictionary 将是 [String: String]