我需要转换键和值的数组,如:
["key1", "value1", "key2", "value2"]
放入字典:
{"key1": "value1", "key2": "value2"}
我可以通过两步遍历数组,分别得到键和值的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"]
另一种方法是使用stride。这假设集合有偶数个元素:
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"]