How to create Dictionary that can hold anything in Key? or all the possible type it capable to hold

前端 未结 8 2070
感动是毒
感动是毒 2020-12-05 04:13

I want to create a Dictionary that does not limit the key type (like NSDictionary)

So I tried

var dict = Dictionary

        
8条回答
  •  旧时难觅i
    2020-12-05 04:27

    I took the liberty of cross-posting / linking to this question on a separate post on the Apple Dev forums and this question is answered here.

    Edit

    This answer from the above link works in 6.1 and greater:

    struct AnyKey: Hashable {
        private let underlying: Any
        private let hashValueFunc: () -> Int
        private let equalityFunc: (Any) -> Bool
    
        init(_ key: T) {
            underlying = key
            // Capture the key's hashability and equatability using closures.
            // The Key shares the hash of the underlying value.
            hashValueFunc = { key.hashValue }
    
            // The Key is equal to a Key of the same underlying type,
            // whose underlying value is "==" to ours.
            equalityFunc = {
                if let other = $0 as? T {
                    return key == other
                }
                return false
            }
        }
    
        var hashValue: Int { return hashValueFunc() }
    }
    
    func ==(x: AnyKey, y: AnyKey) -> Bool {
        return x.equalityFunc(y.underlying)
    }
    

提交回复
热议问题