Swift 2.0 beta字典扩展

ade*_*dev 2 generics macos ios swift swift2

试图创建一个不可变的字典.我们的想法是拥有不可变的键和值数组,然后将它们传递给a

Dictionary constructor: let dict = Dictionary(aStringArray, aSameLengthDoubleArray)

但是,以下代码给出了编译时错误.

extension Dictionary {
    init<T:Hashable,U>(keys: [T], values: [U]) {
        self.init()
        for (index, key) in keys.enumerate() {
            self[key] = values[index]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

错误:

错误:无法下标"Dictionary"类型的值,索引类型为"T"self [key] = values [index]

有人可以对此有所了解吗?

San*_*eep 6

如果您知道Dictionary已经为其关联类型键和值设置了typealases.键应为Key类型,值应为Value类型.就像你在Array中Element类型一样.上面你可以简单地使用Key和Value来实现,

extension Dictionary {
    init(keys: [Key], values: [Value]) {
        self.init()
        for (index, key) in keys.enumerate() {
            self[key] = values[index]
        }
    }
}
let a = Dictionary(keys: [1, 2, 3, 4, 5], values: ["Michael", "Jack", "Kurt", "Jim", "Stewart"])
Run Code Online (Sandbox Code Playgroud)