问题
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