Zaphod
Zaphod

Reputation: 7290

Generic subscript with constraints on associated type leads to "Cannot subscript a value of type..."

Using Swift 4.2, I'm trying to write a generic system to get rid of strings as key of dictionaries to use enums instead.

Here is what I came with:

extension Dictionary where Key == String {
    subscript<T : RawRepresentable>(key: T) -> Value? where T.RawValue == String {
        get { return self[key.rawValue] }
        set { self[key.rawValue] = newValue }
    }
}

This compiles, and is destined to take any RawRepresentable type with a String raw value as key to the subscript for every Dictionary with String as key.

Unfortunately when I do the following, it does not compile:

enum MovieKey: String {
    case movieId = "movie_id"
    case movies = "movies"
}

var dic = [String:String]()
dic[key: MovieKey.movieId] = "abc123" // error

I get the following compilation error: Cannot subscript a value of type '[String : String]' with an index of type '(key: MovieKey)'

Except if I'm mistaken, dic is a Dictionary with String as key, and MovieKey is RawRepresentable and the raw value is String typed...

If someone can explain what I'm doing wrong, thanks in advance.

Upvotes: 0

Views: 197

Answers (1)

David Pasztor
David Pasztor

Reputation: 54745

The issue is that you aren't using subscript correctly. You shouldn't be supplying any argument labels to the subscript call, simply supply the enum value.

dic[MovieKey.movieId] = "abc123" compiles just fine.

Upvotes: 1

Related Questions