[英]Swift: dictionary from array of keys and values
我需要轉換一組鍵和值,例如:
["key1", "value1", "key2", "value2"]
進入字典:
{"key1": "value1", "key2": "value2"}
我可以 go 通過數組一步兩步,分別獲得鍵和值的 n 和 n+1,但是有什么聰明的方法嗎?
謝謝!
您可以將您的集合分成兩個子序列並將它們減少到字典中:
extension Collection {
func unfoldSubSequences(limitedTo maxLength: Int) -> UnfoldSequence<SubSequence,Index> {
sequence(state: startIndex) { start in
guard start < self.endIndex else { return nil }
let end = self.index(start, offsetBy: maxLength, limitedBy: self.endIndex) ?? self.endIndex
defer { start = end }
return self[start..<end]
}
}
}
let kvs = ["key1", "value1", "key2", "value2"]
let dictionary = kvs
.unfoldSubSequences(limitedTo: 2)
.reduce(into: [:]) {
guard $1.count == 2, let key = $1.first, let value = $1.last else { return }
$0[key] = value
}
dictionary // ["key1": "value1", "key2": "value2"]
另一種使用步幅的方法。 這假設您的集合具有偶數個元素:
let kvs = ["key1", "value1", "key2", "value2"]
let dictionary = stride(from: 0, to: kvs.count, by: 2)
.reduce(into: [:]) { $0[kvs[$1]] = kvs[$1+1] }
dictionary // ["key1": "value1", "key2": "value2"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.