Just a sanity check with the community before I file a radar:
In a .h Obj-C file:
@protocol myProto <NSObject>
@end
In a .swift file (that has access to the above protocol definition via bridging header):
class myClass {
// This line compiles fine
var dictOne: [NSObject:Int]?
// This line fails with "Type 'myProto' does not conform to protocol 'Hashable'"
var dictTwo: [myProto:Int]?
}
Inspection of the NSObject class reveals that it (or the NSObjectProtocol that it maps to) does not implement the hashValue method required by the Hashable protocol, nor does it explicity adopt it.
So, somewhere behind the scenes the NSObject is being flagged as Hashable despite this, but does not extend to protocols that adopt NSObject/NSObjectProtocol.
Have I got a bug or am I missing something?
:) Teo
Additional info:
The documentation suggests that:
- A dictionary's key type's only requirements is that it's Hashable and that it implements
==
. - You can indeed use a protocol.
Hash Values for Dictionary Key TypesA type must be hashable in order to be used as a dictionary’s key type—that is, the type must provide a way to compute a hash value for itself. A hash value is an Int value that is the same for all objects that compare equal, such that if a == b, it follows that a.hashValue == b.hashValue.
All of Swift’s basic types (such as String, Int, Double, and Bool) are hashable by default, and all of these types can be used as the keys of a dictionary. Enumeration member values without associated values (as described in Enumerations) are also hashable by default.
NOTE You can use your own custom types as dictionary key types by making them conform to the Hashable protocol from Swift’s standard library. Types that conform to the Hashable protocol must provide a gettable Int property called hashValue, and must also provide an implementation of the “is equal” operator (==). The value returned by a type’s hashValue property is not required to be the same across different executions of the same program, or in different programs. For more information about conforming to protocols, see Protocols.