【问题标题】:Parsing an array with separators into key-values将带有分隔符的数组解析为键值
【发布时间】:2020-01-20 14:50:30
【问题描述】:

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

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

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

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

现在,它变成了Array<Substring>。我想到了可解码并转换了这个array into a dictionary,但它并没有把我带到任何地方。

【问题讨论】:

  • 这些值从何而来?
  • @LeoDabus 在对来自 API 调用的复杂字符串进行正则表达式之后。可能,影响?我想问为什么这很重要。
  • @raurora 也许是因为它可以在“之前”完成,或者可以使用更好的解析。

标签: ios arrays swift parsing decoder


【解决方案1】:

你可以使用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"]

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

【讨论】:

  • Swift 是一种类型推断语言reduce(into: [:])
  • 我猜 JSON 的习惯。
  • 有趣的是它在推断 Anyhashable: Any here
  • 谢谢,@Larme。尽管看到了很多答案,但从未点击过深入了解reduce(into:_:)。感谢您的帮助。
猜你喜欢
  • 2012-10-23
  • 2016-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多