简体   繁体   English

Swift 2.0 Beta字典扩展

[英]Swift 2.0 beta Dictionary extension

Trying to create an immutable Dictionary. 试图创建一个不变的字典。 The idea is to have immutable arrays of keys and values each and then pass them to a 这个想法是让每个键和值具有不可变的数组,然后将它们传递给

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

The following code however gives a compile time error. 但是,以下代码给出了编译时错误。

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

Error: 错误:

error: cannot subscript a value of type 'Dictionary' with an index of type 'T' self[key] = values[index] 错误:无法使用索引类型为T的“字典”类型下标self [key] = values [index]

Can someone throw some light on this? 有人可以对此有所启发吗?

If you know that Dictionary already has typealiases for its associated types key and values. 如果您知道Dictionary已经为其关联的类型的键和值使用了类型别名。 The keys should be of type Key and value should be of type Value . 键应该是Key类型,而值应该是Value类型。 Just like you would have Element type in Array . 就像您在Array中拥有Element类型一样。 The above thing you could achieve simply using Key and Value as so, 只需使用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"])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM