I'm trying to parse an estimated travel duration and distance between two waypoints using Google Directions API. Tap on this to see an example of data received.
private class func parseTravelData(
data: AnyObject!,
mode: ESTMode,
completion: (NSDictionary?) -> Void) {
var receivedData = data as? NSDictionary
if let routes = receivedData?["routes"] as? NSArray {
if routes.count > 0 {
if let legs = routes[0]["legs"] as? NSArray {
if legs.count > 0 {
var dur: String? = nil
if let duration = legs[0]["duration"] as? NSDictionary {
if let v = duration["value"] as? Float {
if v > ConnectionManager().timeMax && mode == .Walking {
completion(nil) // resend using drive mode
}
else {
if let t = duration["text"] as? String {
dur = t
}
}
}
}
if let d = dur {
if let distance = legs[0]["distance"] as? NSDictionary {
if let dist = distance["text"] as? String {
completion([
"duration": d,
"distance": dist])
}
}
}
}
}
}
}
}
This code works fine but looks awful. What I need is do nothing if data is incorrect. I can't come anything up with it. The main goal is avoiding of getting different unwrapping errors if something is wrong. I would greatly appreciate any help.