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
Dictionaryhas two generic parametersKeyandValue, andKeymay not beString.This works:
For ADDED part.
If you introduce a new generic parameter
Tin extension ofDictionary, the method needs to work for all possible combination ofKey(:Hashable),ValueandT(:Hashable).KeyandTmay not be the same type.(For example,
Keymay beStringandTmay beInt(bothHashable). You know you cannot subscript withIntwhenKeyisString.)So, you cannot subscript with
keyof 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.