Swift Dictionary access value using key within extension

十年热恋 提交于 2019-12-25 04:26:54

问题


It turns out that within a Dictionary extension, the subscript is quite useless since it says Ambiguous reference to member 'subscript'. It seems I'll either have to do what Swift does in its subscript(Key) or call a function. Any ideas?

For example,

public extension Dictionary {
    public func bool(_ key: String) -> Bool? {
        return self[key] as? Bool
    }
}

won't work, since the subscript is said to be ambiguous.

ADDED My misunderstanding came from the fact that I assumed that Key is an AssociatedType instead of a generic parameter.


回答1:


Swift type Dictionary has two generic parameters Key and Value, and Key may not be String.

This works:

public extension Dictionary {
    public func bool(_ key: Key) -> Bool? {
        return self[key] as? Bool
    }
}

let dict: [String: Any] = [
    "a": true,
    "b": 0,
]
if let a = dict.bool("a") {
    print(a) //->true
}
if let b = dict.bool("b") {
    print(b) //not executed
}

For ADDED part.

If you introduce a new generic parameter T in extension of Dictionary, the method needs to work for all possible combination of Key(:Hashable), Value and T(:Hashable). Key and T may not be the same type.

(For example, Key may be String and T may be Int (both Hashable). You know you cannot subscript with Int when Key is String.)

So, you cannot subscript with key of type T.


For updated ADDED part.

Seems to be a reasonable misunderstanding. And you have found a good example that explains protocol with associated type is not just a generic protocol.



来源:https://stackoverflow.com/questions/41133595/swift-dictionary-access-value-using-key-within-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!