J.Doe J.Doe - 2 months ago 16
iOS Question

Type '(key: String, value: Any)' has no subscript members

I loop through an array of dictionary with this code.

if let users = object["usersList"] as? [Any] {
for user in users as! [String : Any] {
print(user["id"])
}
}


Each dictionary has an
id
attribute. When I want to access it with
user["id"]
, I get the error:


Type '(key: String, value: Any)' has no subscript members

Answer Source

You are casting the array to a dictionary which cannot work.

The easiest solution is to (optional down)cast users to specific [[String : Any]]

if let users = object["usersList"] as? [[String : Any]] {
    for user in users {
        print(user["id"])
    }
}