-2

I have an array of dictionaries that looks like the following:

locationArray [{
    annotation = "<MKPointAnnotation: 0x7fb75a782380>";
    country = Canada;
    latitude = "71.47385399229037";
    longitude = "-96.81064609999999";
}, {
    annotation = "<MKPointAnnotation: 0x7fb75f01f6c0>";
    country = Mexico;
    latitude = "23.94480686844645";
    longitude = "-102.55803745";
}, {
    annotation = "<MKPointAnnotation: 0x7fb75f0e6360>";
    country = "United States of America";
    latitude = "37.99472997055178";
    longitude = "-95.85629150000001";
}]

I would like sort on longitude.

Paul S.
  • 1,342
  • 4
  • 22
  • 43

1 Answers1

2

For example:

let locationArray: [[String: AnyObject]] = [
    ["country": "Canada",
    "latitude": "71.47385399229037",
    "longitude": "-96.81064609999999"],
    ["country": "Mexico",
    "latitude": "23.94480686844645",
    "longitude": "-102.55803745"],
    ["country": "United States of America",
    "latitude": "37.99472997055178",
    "longitude": "-95.85629150000001"]
]

let sortedArray = locationArray.sort { (first, second) in
    return first["longitude"]?.doubleValue < second["longitude"]?.doubleValue
}

print(sortedArray.map { $0["country"] })

But a better approach is to parse every position dictionary into a custom object and sort those custom objects:

struct Location {
    let country: String
    let latitude: Double
    let longitude: Double

    init(dictionary: [String: AnyObject]) {
        country = (dictionary["country"] as? String) ?? ""
        latitude = (dictionary["latitude"] as? NSString)?.doubleValue ?? 0
        longitude = (dictionary["longitude"] as? NSString)?.doubleValue ?? 0
    }
}

let locations = locationArray.map { Location(dictionary: $0) }

let sortedArray = locations.sort { (first, second) in
    return first.longitude < second.longitude
}

print(sortedArray.map { $0.country })
Sulthan
  • 128,090
  • 22
  • 218
  • 270