如何在嵌套的Object SWIFT中获取值

时间:2016-10-31 21:43:45

标签: json swift

我正在尝试访问嵌套对象中的值。 (基本上是一个包含对象的数组,其中一个对象包含对象作为值

(result, response, error) -> Void in
        if let err = error {
            print("ERROR ---------------------->", err)
        } else if let tempResult = result as? [NSDictionary] {

            print(tempResult.count)

            for details in tempResult {
                print("----------------->")
                print(details["details"]!) //works fine
                print(details["details"]["price"]!) //will not compile
                }
}

这是我收到的编译器警告

print(details["version"]["type"]!) // Type 'Any?' has no subscript members

这是我正在解析的数据的树结构

[ 
 { name: 'Mischief',
 price: 790000,
 link: 'xxxxxxx',
 details: 
      { price: '7390000', web: 'link', info: 'details' } },

 { name: 'Ify',
 price: 190000,
 link: 'xxxxxxx',
 details: 
      { price: '690000', web: 'link', info: 'details' } },

 { name: 'Connor',
 price: 980000,
 link: 'xxxxxxx',
 details: 
      { price: '120000', web: 'link', info: 'details' } }
]

1 个答案:

答案 0 :(得分:1)

与往常一样,请不要使用Foundation集合类型。你扔掉了类型信息。除非别无选择,否则请使用Swift本机类型。

编译器需要知道所有下标对象的类型,details的值似乎是[String:String]

(result, response, error) -> Void in
    if let err = error {
        print("ERROR ---------------------->", err)
    } else if let tempResult = result as? [[String:Any]] {

        print(tempResult.count)

        for anItem in tempResult {
            print("----------------->")
            if let details = anItem["details"] as? [String:String] {
               print(details["price"]!)
            }
        }
    }