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

前端 未结 8 2078
感动是毒
感动是毒 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

    Hashable is just a protocol so you can't specify it directly as a type for the Key value. What you really need is a way of expressing "any type T, such that T implements Hashable. This is handled by type constraints in Swift:

    func makeDict(arr: T[]) {
      let x = Dictionary()
    }
    

    This code compiles.

    AFAIK, you can only use type constraints on generic functions and classes.

提交回复
热议问题