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.
Swift type
Dictionary
has two generic parametersKey
andValue
, andKey
may not beString
.This works:
For ADDED part.
If you introduce a new generic parameter
T
in extension ofDictionary
, the method needs to work for all possible combination ofKey
(:Hashable
),Value
andT
(:Hashable
).Key
andT
may not be the same type.(For example,
Key
may beString
andT
may beInt
(bothHashable
). You know you cannot subscript withInt
whenKey
isString
.)So, you cannot subscript with
key
of typeT
.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.