将Swift数组转换为带索引的字典
我使用的是Xcode 6.4 我有一个UIView数组,我想转换成带有键的字典将Swift数组转换为带索引的字典,swift,functional-programming,swift2,swift3,Swift,Functional Programming,Swift2,Swift3,我使用的是Xcode 6.4 我有一个UIView数组,我想转换成带有键的字典“v0”、“v1”…。像这样: var dict = [String:UIView]() for (index, view) in enumerate(views) { dict["v\(index)"] = view } dict //=> ["v0": <view0>, "v1": <view1> ...] 这感觉更好,但我得到了一个错误:无法将“UIView”类型的值分配给“U
“v0”、“v1”…
。像这样:
var dict = [String:UIView]()
for (index, view) in enumerate(views) {
dict["v\(index)"] = view
}
dict //=> ["v0": <view0>, "v1": <view1> ...]
这感觉更好,但我得到了一个错误:无法将“UIView”类型的值分配给“UIView”类型的值。
我用UIView
(即:[String]->[String:String]
)以外的对象尝试过这个方法,我得到了相同的错误
有什么清理建议吗?试试下面的方法:
reduce(enumerate(a), [String:UIView]()) { (var dict, enumeration) in
dict["\(enumeration.index)"] = enumeration.element
return dict
}
Xcode 8•Swift 2.3
extension Array where Element: AnyObject {
var indexedDictionary: [String:Element] {
var result: [String:Element] = [:]
for (index, element) in enumerate() {
result[String(index)] = element
}
return result
}
}
Xcode 8•Swift 3.0
extension Array {
var indexedDictionary: [String: Element] {
var result: [String: Element] = [:]
enumerated().forEach({ result[String($0.offset)] = $0.element })
return result
}
}
Xcode 9-10•Swift 4.0-4.2
使用Swift 4reduce(into:)
方法:
extension Collection {
var indexedDictionary: [String: Element] {
return enumerated().reduce(into: [:]) { $0[String($1.offset)] = $1.element }
}
}
使用Swift 4
字典(UniqueKeyWithValues:)
初始值设定项并从枚举集合传递新数组:
extension Collection {
var indexedDictionary: [String: Element] {
return Dictionary(uniqueKeysWithValues: enumerated().map{(String($0),$1)})
}
}
我不敢相信这能解决它!你知道为什么会这样吗?我看到的关于闭包的大多数文档都在parameters.dict中省略了
var
。如果要更改它,需要将其声明为变量。:)啊,这很有道理。非常感谢,今晚我已经在这里呆了太久了:)
extension Collection {
var indexedDictionary: [String: Element] {
return Dictionary(uniqueKeysWithValues: enumerated().map{(String($0),$1)})
}
}