简体   繁体   中英

Type 'Any' has no subscript members Swift 3

let message = JSON((userInfo["aps"]?["alert"])!).stringValue

When I try building I get "Type 'Any' has no subscript members"

Trying to convert to Swift 3, but can't seem to solve this error.

The compiler doesn't know what type userInfo["aps"] is. So it's assuming it's of type Any .

You can't call a subscript, ie, ["alert"] on Any . So it complains.

You need to unwrap it as something hashable. An example:

if let dict = userInfo["aps"] as? [String : AnyObject] {
     let message = dict["alert"]
}

an alternate solution to Frankies answer is this oneliner:

let message = (userInfo["aps"] as? [AnyHashable: Any])?["alert"] as? String ?? ""

in the end you have the message or an empty string if there is no message (or if the json structure is not as you expected)...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM