How are Int and String accepted as AnyHashable?

前端 未结 3 1051
面向向阳花
面向向阳花 2021-01-05 01:18

How come I can do this?

    var dict = [AnyHashable : Int]()
    dict[NSObject()] = 1
    dict[\"\"] = 2

This implies that NSObject

3条回答
  •  时光说笑
    2021-01-05 02:08

    You can find this code, when you cmd-click on [ or ] of dict[NSObject()] = 1 in the Swift editor of Xcode (8.2.1, a little different in 8.3 beta):

    extension Dictionary where Key : _AnyHashableProtocol {
    
        public subscript(key: _Hashable) -> Value?
    
        public mutating func updateValue(_ value: Value, forKey key: ConcreteKey) -> Value?
    
        public mutating func removeValue(forKey key: ConcreteKey) -> Value?
    }
    

    _AnyHashableProtocol and _Hashable are hidden types, so you may need to check the Swift source code. Simply:

    • _Hashable is a hidden super-protocol of Hashable, so, Int, String, NSObject or all other Hashable types conform to _Hashable.

    • _AnyHashableProtocol is a hidden protocol, where AnyHashable is the only type which conforms to _AnyHashableProtocol.

    So, the extension above is very similar to this code in Swift 3.1.

    extension Dictionary where Key == AnyHashable {
    
        //...
    }
    

    You see, when you write such code like this:

        var dict = [AnyHashable : Int]()
        dict[NSObject()] = 1
        dict[""] = 2
    

    You are using the subscript operator defined in the extension.

提交回复
热议问题