JABD
JABD

Reputation: 640

Swift: "Any" does not have member named element

So not sure what is wrong here, but swift throws me error in this case, and gives me no output for foo[0]

let bar: [String: Any] = [
    "questions":[
        ["id":1,"text":"What is your name?"],
        ["id":2,"text":"What is the last name?"]
    ],
    "status":"baz",
    "registered": true
]

let foo: [[String: Any]] = bar["questions"] as [[String: Any]]

foo[0]

Although it does work if I do following -

let bar: [String: String] = [
    "questions":[
        ["id":"1","text":"What is your name?"],
        ["id":"2","text":"What is the last name?"]
    ],
    "status":"AUTHENTICATE",
    "registered": true
]

let foo: [[String: String]] = bar["questions"] as [[String: String]]

foo[0]

I changed my ids to string (notice I have not touched boolean) and also Any to string.

Please shed some light for this behavior.

Thank you

Upvotes: 1

Views: 1318

Answers (1)

slazyk
slazyk

Reputation: 1792

If you write a complicated dictionary literal like ["id":1,"text":"What is your name?"] without annotating the type in some way it will default to creating an NSDictionary.

NSDictionary in Swift is bridged to [NSObject: AnyObject]. Force casting it to [String: Any] will crash with error "can't reinterpretCast values of different sizes". But casting NSDictionary to [String: AnyObject] will work just fine.

So you can either use [String: AnyObject] or NSDictionary instead of [String: Any], or you can hint the type of desired dictionaries, for example like this:

let bar: [String: Any] = [
    "questions":[
        ["id":1,"text":"What is your name?"] as [String: Any],
        ["id":2,"text":"What is the last name?"]
    ],
    "status":"baz",
    "registered": true
]

or like this

let bar: [String: Any] = [
    "questions":[
        ["id":1,"text":"What is your name?"],
        ["id":2,"text":"What is the last name?"]
    ] as [[String: Any]],
    "status":"baz",
    "registered": true
]

Upvotes: 2

Related Questions