jglasse
jglasse

Reputation: 1206

Can't traverse array element of Dictionary of <String: Any>

Trying to figure out why this throws an error ("Cannot subscript a value of type 'inout Dictionary') at the for loop below in Xcode 8.1:

var fooDict = Dictionary<String, Any>()
fooDict["test"] = "I'm a string"
fooDict["numberTest"] = "12345"
fooDict["arrayTest"] = [1,3,4,"five"]

for item in (fooDict["arrayTest"] as! Array)
{
print(item)

}

Upvotes: 0

Views: 55

Answers (2)

Rob Napier
Rob Napier

Reputation: 299345

The error here is confusing and pointing you in the wrong direction. You can't have just Array in Swift. It has to be an array of something specific. In this case, you mean an array of Any, so you have to say so:

for item in (fooDict["arrayTest"] as! [Any])

Upvotes: 3

Prientus
Prientus

Reputation: 733

You have to indicate that the array is of type Any. Like this:

for item in (fooDict["arrayTest"] as! Array<Any>)
{
    print(item)
}

Upvotes: 2

Related Questions