How do I manipulate nested dictionaries in Swift, e.g. JSON data?

前端 未结 3 992
我在风中等你
我在风中等你 2020-12-09 11:01

I\'m using NSJSONSerialization to parse JSON in a Swift application. However, the returned dictionary consists of a complicated, deeply nested structure, making it impractic

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-09 11:30

    In Obj-C we could write,

    cityName = myDictionary[@"photos"][@"region"][@"city"]

    As several here have discovered, the above does not apply in Swift, at least it never has for me.

    Here's how you do this in Swift for accessing three indices in an NSDictionary for a String,

    let cityName = ((myDictionary!["photos"] as NSDictionary)["region"]! as NSDictionary)["city"]! as String`

    I hope that in the next update to Swift all of that can be reduced to what we had in Obj-C.

提交回复
热议问题