2

I am getting error like "ambiguous reference to member subscript" in a dictionary which may contains array type values, when I try to access array type values then getting error. Please check below code.

var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
"Layme": ["Engineer", "Docter"] 
] as [String : Any]


occupations["Jayne"] = "Public Relations"
var arrOfLayme = occupations["Layme"] as! Array //getting error here, If I use NSArray instead of array all will work as expacted
print(valueOcc[0])

when I used NSArray type this code going well as below line, I want to do in pure swift way, don't want to add Objective-c.

var arrOfLayme = occupations["Layme"] as! NSArray

2 Answers 2

5

Try this:

var occupations:[String:Any] = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
    "Layme": ["Engineer", "Docter"]
    ]

occupations["Jayne"] = "Public Relations"


var arrOfLayme = occupations["Layme"] as! [String]
print(arrOfLayme)

//More safe
if let arr = occupations["Layme"] as? [String] {
    print(arr)
}
Sign up to request clarification or add additional context in comments.

Comments

2

Swift is a strongly typed language, therefore, you can not access to generic containers, like you were able to in Objective C with NSArray.

You need to explicitly tell the complier, what sort of Array are you expecting to be retrieved from the dictionary.

Do the following:

import Foundation

// Delcare type next to the variable, not at the end
// Makes the code more readable
var occupations: [String : Any] = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
    "Layme": ["Engineer", "Docter"] 
    ]

occupations["Jayne"] = "Public Relations"

// Safe reading
if let arrOfLayme = occupations["Layme"] as? [String] {
    print(arrOfLayme)
}

// Force casting option 1
var arrOfLayme = occupations["Layme"] as! Array<String>

// Force casting option 2
var arrOfLayme2 = occupations["Layme"] as! [String] 

1 Comment

Thanks @dirtydanee

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.