Remedy_man Remedy_man - 1 month ago 10
JSON Question

How to obtain value within nested Object SWIFT

I am trying to access a value within a nested object. (Basically an array containing objects, of which one of the objects contains objects as values)

(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
}
}


This is the compiler warning I was getting

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


This is the tree structure of the data i am parsing

[
{ 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' } }
]

Answer

As always, please do not use Foundation collection types. You throw away the type information. Use Swift native types unless you have no choice.

The compiler needs to know the type of all subscripted objects, the value of details seems to be [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"]!)
            }
        }
    }
Comments