GiorgioE
GiorgioE

Reputation: 204

Error when getting value from constant : Ambiguous reference to member 'subscript'

I am using enum and tuple with value of enum case. I've trouble with getting value from [String: String] constant.

I don't know how to fix it, it has to be a trap, but I don't know where, as the key is surely string:

enum DictTypes : String {
        case settings
        case options
        case locations
    }
    enum FileTypes : String {
        case json
        case pList
    }

    func getCodebookUrlComponent() -> String
    {
        var FileSpecs: (
                dictType: DictTypes,
                fileType: FileTypes,
                redownload: Bool
            ) = (.settings, .json, true)

        let codebooks = [
            "settings" : "settings",
            "options" : "options"
        ]

        let key = self.FileSpecs.dictType // settings or options

        if let urlComponent = codebooks[key] {

            return urlComponent
        }

        return ""
    }

This line if let urlComponent = codebooks[key] comes with an error:

Ambiguous reference to member 'subscript'

Upvotes: 2

Views: 597

Answers (2)

pedrouan
pedrouan

Reputation: 12910

Since value from enum case is surely string, I would type it like this:

let key = FileSpecs.dictType.rawValue // "settings" or "options"

or

let key = String(describing: FileSpecs.dictType) 

return codebooks[key]!

Upvotes: 1

Oleg Gordiichuk
Oleg Gordiichuk

Reputation: 15512

You should use .rawValue for this case :

if let urlComponent = codebooks[key.rawValue]{
   return urlComponent
}

This problem occurs because of the let key = self.FileSpecs.dictType in this line you receive key that is FileSpecs type. And subscript that is implemented in the Array will not conform for that value type.

rawValue in you're case return String value that you assign in you're enum.

Upvotes: 3

Related Questions