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

前端 未结 8 2059
感动是毒
感动是毒 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条回答
  •  爱一瞬间的悲伤
    2020-12-05 04:31

    This doesn't exactly answer the question, but has helped me.

    The general answer would be implement Hashable for all your types, however that can be hard for Protocols because Hashable extends Equatable and Equatable uses Self which imposes severe limitations on what a protocol can be used for.

    Instead implement Printable and then do:

    var dict = [String: Int]
    dict[key.description] = 3
    

    The implementation of description has to be something like:

    var description : String {
        return "[\(), \(), ...]"
    }
    

    Not a perfect answer, but the best I have so far :(

提交回复
热议问题