Ios Swift:来自键和值数组的字典
我需要转换一个键值数组,例如:Ios Swift:来自键和值数组的字典,ios,arrays,swift,dictionary,Ios,Arrays,Swift,Dictionary,我需要转换一个键值数组,例如: [“键1”、“值1”、“键2”、“值2”] 进入字典: extension Collection { func unfoldSubSequences(limitedTo maxLength: Int) -> UnfoldSequence<SubSequence,Index> { sequence(state: startIndex) { start in guard start < self
[“键1”、“值1”、“键2”、“值2”]
进入字典:
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]
}
}
}
{“key1”:“value1”,“key2”:“value2”}
我可以通过两步遍历数组,分别得到key和value的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 = stride(from: 0, to: kvs.count, by: 2)
.reduce(into: [:]) { $0[kvs[$1]] = kvs[$1+1] }
dictionary // ["key1": "value1", "key2": "value2"]
您可以更有效地使用
stride
、map
、filter
等功能,但您仍将执行相同的操作“按两步遍历数组,并为键和值获取n和n+1”。我不认为在不牺牲大量可读性的情况下,你可以避免写数字“2”并得到n和n+1。