GiorgioE GiorgioE - 2 months ago 39
Swift Question

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'

Answer

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.