相关疑难解决方法(0)

如何从元组数组创建字典?

假设我有可以识别的对象数组,我想从中创建字典.我可以轻松地从我的数组中获取元组:

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)

dictionary tuples ios swift

21
推荐指数
4
解决办法
7439
查看次数

错误:传递reduce函数的不可变值

我正在尝试执行以下代码将元组数组转换为字典但我收到编译错误说:

类型'[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)

reduce dictionary swift

8
推荐指数
2
解决办法
2686
查看次数

Enumerating dictionary in Swift

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)

dictionary enumeration swift

8
推荐指数
1
解决办法
5363
查看次数

标签 统计

dictionary ×3

swift ×3

enumeration ×1

ios ×1

reduce ×1

tuples ×1