tryingtolearn tryingtolearn - 4 months ago 8
iOS Question

Extracting values from anyobject dictionary into array

My other question was marked as being identical to another but it didn't answer the problem I was having.

Here is the code:

if status == "OK" {


self.selectedRoute = (dictionary["routes"] as! Array<Dictionary<NSObject, AnyObject>>)[0]
self.overviewPolyline = self.selectedRoute["overview_polyline"] as! Dictionary<NSObject, AnyObject>

let legs = self.selectedRoute["legs"] as! Array<Dictionary<NSObject, AnyObject>>
let steps = legs[0]["steps"]!

for i in 0...steps.count - 1 {
let step_coordinate = steps[i]["start_location"]!
print(step_coordinate!["lat"]!!)

}

}


The print statement gives this result

40.7609205
40.7640121
40.7595325
40.7501637
40.7481923
40.7393448
40.7252038
40.7225337
40.718295


but if I swap the print statement out to grab the values and put them in an array I get the fatal error: found nil.

Can someone explain why this is the case? How can I grab these values if not through a for loop?

Answer

Here's a cleaner version of your code.

Rules:

  1. Don't force unwrap anything!
  2. Optionally cast values coming from [NSObject: AnyObject] lookups.
  3. Use guard statements and if let to safely unwrap optionals.
  4. Don't index arrays that might be empty without checking first.

if status == "OK" {
    guard let routes = dictionary["routes"] as? [[NSObject: AnyObject]] else { return }
    self.selectedRoute = routes.first ?? [:]

    self.overviewPolyline = self.selectedRoute["overview_polyline"] as? [NSObject: AnyObject] ?? [:]

    guard let legs = self.selectedRoute["legs"] as? [[NSObject: AnyObject]] else { return }

    let firstleg = legs.first ?? [:]
    guard let steps = firstleg["steps"] as? [[NSObject: AnyObject]] else { return }

    for step in steps {
        if let step_coordinate = step["start_location"] as? [NSObject: AnyObject] {
            if let lat = step_coordinate["lat"] as? Double {
                print(lat)

                // append lat to array of lats
                lats.append(lat)
            }
        }
    }
}