Home > Enterprise >  RangeExpression issue for Key of Dictionary even the Key is Hashable
RangeExpression issue for Key of Dictionary even the Key is Hashable

Time:01-04

I am getting a error from Xcode like this Subscript 'subscript(_:)' requires that 'T' conform to 'RangeExpression' when I use this code below:

func test<T>(key: T) where T: Hashable {

    let dic: Dictionary<String, String> = ["1": "a"]
    
    if let unwrappedValue = dic[key] {
        print(unwrappedValue)
    }
 
}

I really do not see any reason that Xcode should complain! Because the Apple documentation says:

@frozen public struct Dictionary<Key, Value> where Key : Hashable { ...

So as you can see in my code, I gave what should be done! So why am I receiving this error?!

CodePudding user response:

The error message isn't great, but the issue is that T isn't related to the Key type of your dic (which is always String).

Your function is generic over any unbounded T, which allows a caller to pass non-String values to key, which wouldn't be compatible with your dic.

You either need to make your dictionary generic, or your function non-generic.

  •  Tags:  
  • Related