swift - How to create Dictionary that can hold anything in Key? or all the possible type it capable to hold -
i want create dictionary not limit key type (like nsdictionary)
so tried
var dict = dictionary<any, int>() and
var dict = dictionary<anyobject, int>() resulting
error: type 'any' not conform protocol 'hashable' var dict = dictionary<any, int>() ^ <repl>:5:12: error: cannot convert expression's type '<<error type>>' type '$t1' var dict = dictionary<any, int>() ^~~~~~~~~~~~~~~~~~~~~~ ok, use hashable
var dict = dictionary<hashable, int>() but
error: type 'hashable' not conform protocol 'equatable' var dict = dictionary<hashable, int>() ^ swift.equatable:2:8: note: '==' requirement refers 'self' type func ==(lhs: self, rhs: self) -> bool ^ swift.hashable:1:10: note: type 'hashable' not conform inherited protocol 'equatable.protocol' protocol hashable : equatable ^ <repl>:5:12: error: cannot convert expression's type '<<error type>>' type '$t1' var dict = dictionary<hashable, int>() ^~~~~~~~~~~~~~~~~~~~~~~~~~~ so hashable inherited equatable not conform equatable??? don't understand...
anyway, keep trying
typealias keytype = protocol<hashable, equatable> // keytype both hashable , equatable var dict = dictionary<keytype, int>() // happy? with no luck
error: type 'keytype' not conform protocol 'equatable' var dict = dictionary<keytype, int>() ^ swift.equatable:2:8: note: '==' requirement refers 'self' type func ==(lhs: self, rhs: self) -> bool ^ swift.hashable:1:10: note: type 'keytype' not conform inherited protocol 'equatable.protocol' protocol hashable : equatable ^ <repl>:6:12: error: cannot convert expression's type '<<error type>>' type '$t1' var dict = dictionary<keytype, int>() ^~~~~~~~~~~~~~~~~~~~~~~~~~ i lost now, how can make compiler happy code?
i want use dictionary like
var dict = dictionary<any, int>() dict[1] = 2 dict["key"] = 3 dict[someenum.somevalue] = 4 i know can use dictionary<nsobject, int>, not want.
swift 3 update
you can use anyhashable type-erased hashable value, created scenarios this:
var dict = dictionary<anyhashable, int>()
Comments
Post a Comment