假设我有可以识别的对象数组,我想从中创建字典.我可以轻松地从我的数组中获取元组:
let tuples = myArray.map { return ($0.id, $0) }
Run Code Online (Sandbox Code Playgroud)
但是我看不到字典的初始化器来获取元组数组.我错过了什么吗?我是否为此功能创建了字典扩展(事实上它并不难,但我认为它会默认提供)或者有更简单的方法吗?
有扩展代码
extension Dictionary
{
public init (_ arrayOfTuples : Array<(Key, Value)>)
{
self.init(minimumCapacity: arrayOfTuples.count)
for tuple in arrayOfTuples
{
self[tuple.0] = tuple.1
}
}
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试执行以下代码将元组数组转换为字典但我收到编译错误说:
类型'[String:String]'的不可变值仅包含名为'updateValue'的变异成员
var array = [("key0", "value0"), ("key1", "value1")]
var initial = [String: String]()
var final = array.reduce(initial) { (dictionary, tuple) in
dictionary.updateValue(tuple.0, forKey: tuple.1)
return dictionary
}
Run Code Online (Sandbox Code Playgroud)
为什么如果initial被声明为var?它与reduce 的签名上的@noescape有关吗?
func reduce<U>(initial: U, combine: @noescape (U, T) -> U) -> U
Run Code Online (Sandbox Code Playgroud) I guess I noticed a bug in the Swift Dictionary enumeration implementation.
The output of this code snippet:
var someDict:[Int:String] = [1:"One", 2:"Two", 3:"Three"]
for (key, value) in someDict.enumerated() {
print("Dictionary key \(key) - Dictionary value \(value)")
}
Run Code Online (Sandbox Code Playgroud)
should be:
Dictionary key 2 - Dictionary value Two
Dictionary key 3 - Dictionary value Three
Dictionary key 1 - Dictionary value One
Run Code Online (Sandbox Code Playgroud)
instead of:
Dictionary key 0 - Dictionary value (key: 2, value: "Two")
Dictionary key 1 - Dictionary value (key: …Run Code Online (Sandbox Code Playgroud)