How to retrieve specific value from an array

153 Views Asked by At

I am making a request to an API and the results being returned is an array. The issue I have is that the only value I am interested in is the elevation. However, if I append the results to an array, each value in the array looks like this:

elevation = 515;
latitude = 10;
longitude = 10;

Obviously, the returned results would have been a lot easier if it was a dictionary of results and I could query the key value.

An example of the results being returned:

(key: "results", value: <__NSArrayI 0x2801cdc40>(
{
elevation = 515;
latitude = 10;
longitude = 10;
},
{
elevation = 545;
latitude = 20;
longitude = 20;
}))

How can I get the value of elevation only?

Code for extracting response data:

if let data = data,
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
     for items in json {
         print("Keys = \(items.key)")
         print("Value: \(items)")
      }
 }
1

There are 1 best solutions below

0
Chris On

So I figured out what the issue was in my original code. To retrieve only the elevation value this is the approach, it was the initial key 'results' that I got caught out with:

do {
       if let data = data,
       let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
       let results = json["results"] as? [[String:Any]]
       for items in results! {
             let elevationResult = items["elevation"] as! Int
             print("ELEVATION: \(elevationResult)")
        }
    }
    completion(true, "Elevation Data Successfully Retrieved", "Success")
 }