【问题标题】:Convert Swift Array to Dictionary with indexes [duplicate]将 Swift 数组转换为带有索引的字典 [重复]
【发布时间】:2015-10-05 11:18:24
【问题描述】:

我使用的是 Xcode 6.4

我有一个 UIViews 数组,我想转换为带有键 "v0", "v1"... 的字典。像这样:

var dict = [String:UIView]()
for (index, view) in enumerate(views) {
  dict["v\(index)"] = view
}
dict //=> ["v0": <view0>, "v1": <view1> ...]

这行得通,但我正试图以更实用的风格来做到这一点。我想我必须创建dict 变量让我很困扰。我很想像这样使用enumerate()reduce()

reduce(enumerate(views), [String:UIView]()) { dict, enumeration in
  dict["v\(enumeration.index)"] = enumeration.element // <- error here
  return dict
}

这感觉更好,但我得到了错误:Cannot assign a value of type 'UIView' to a value of type 'UIView?' 我已经尝试过使用 UIView 以外的对象(即:[String] -&gt; [String:String]),我得到了同样的错误。

对清理这个有什么建议吗?

【问题讨论】:

    标签: swift functional-programming swift2 swift3


    【解决方案1】:

    试试这样:

    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:) 方法:

    extension Collection  {
        var indexedDictionary: [String: Element] {
            return enumerated().reduce(into: [:]) { $0[String($1.offset)] = $1.element }
        }
    }
    

    使用 Swift 4 Dictionary(uniqueKeysWithValues:) 初始化器并从枚举集合中传递一个新数组:

    extension Collection {
        var indexedDictionary: [String: Element] {
            return Dictionary(uniqueKeysWithValues: enumerated().map{(String($0),$1)})
        }
    }
    

    【讨论】:

    • 我不敢相信这能解决问题!你知道为什么会这样吗?我在闭包上看到的大部分文档都在参数中省略了var
    • dict 默认为常量。如果你想改变它,你需要将它声明为变量。 :)
    • 啊,这很有道理。非常感谢,今晚我在这里待得太久了:)
    猜你喜欢
    • 1970-01-01
    • 2022-10-06
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 2018-10-29
    • 2021-02-14
    相关资源
    最近更新 更多