[英]Parsing an array with separators into key-values
我正在嘗試使用 Swift 5 安全地將數組解析為鍵值。這是一個示例-
["BirthDate=1976-09-11", "Name=Smith", "Status=Alive"]
或者,也許 go 和一個二維數組,如果在上面使用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]
}
Output:
$> ["Status": "Alive", "Name": "Smith", "BirthDate": "1976-09-11"]
編輯: 正如@Leo Dabus 所說,第一行可以寫成let dictionary = array.reduce(into: [:]) {... }
,然后dictionary
將是[AnyHashable: Any]
,或者它可以是let dictionary = array.reduce(into: [String: String]()) {... }
和dictionary
將是一個[String: String]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.