使用索引将 Swift 数组转换为字典 [英] Convert Swift Array to Dictionary with indexes
问题描述
我使用的是 Xcode 6.4
I'm using Xcode 6.4
我有一个 UIView 数组,我想转换为带有键 "v0", "v1"...
的字典.像这样:
I have an array of UIViews and I want to convert to a Dictionary with keys "v0", "v1"...
. Like so:
var dict = [String:UIView]()
for (index, view) in enumerate(views) {
dict["v(index)"] = view
}
dict //=> ["v0": <view0>, "v1": <view1> ...]
这行得通,但我正在尝试以更实用的风格来实现.我想我必须创建 dict
变量让我很困扰.我喜欢像这样使用 enumerate()
和 reduce()
:
This works, but I'm trying to do this in a more functional style. I guess it bothers me that I have to create the dict
variable. I would love to use enumerate()
and reduce()
like so:
reduce(enumerate(views), [String:UIView]()) { dict, enumeration in
dict["v(enumeration.index)"] = enumeration.element // <- error here
return dict
}
这感觉更好,但我收到错误:无法将UIView"类型的值分配给UIView"类型的值?
>UIView(即:[String] -> [String:String]
)我得到同样的错误.
This feels nicer, but I'm getting the error: Cannot assign a value of type 'UIView' to a value of type 'UIView?'
I have tried this with objects other an UIView
(ie: [String] -> [String:String]
) and I get the same error.
有什么清理它的建议吗?
Any suggestions for cleaning this up?
推荐答案
试试这个:
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 4 reduce(into:)
方法:
Using Swift 4 reduce(into:)
method:
extension Collection {
var indexedDictionary: [String: Element] {
return enumerated().reduce(into: [:]) { $0[String($1.offset)] = $1.element }
}
}
<小时>
使用 Swift 4 Dictionary(uniqueKeysWithValues:)
初始化器并从枚举集合中传递一个新数组:
Using Swift 4 Dictionary(uniqueKeysWithValues:)
initializer and passing a new array from the enumerated collection:
extension Collection {
var indexedDictionary: [String: Element] {
return Dictionary(uniqueKeysWithValues: enumerated().map{(String($0),$1)})
}
}
这篇关于使用索引将 Swift 数组转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!