Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

RangeExpression issue for Key of Dictionary even the Key is Hashable

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 { …

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading