如何对一组字典进行排序

时间:2016-07-14 17:25:25

标签: arrays swift dictionary

我有一系列字典,如下所示:

customlogger/

我想依靠经度。

1 个答案:

答案 0 :(得分:2)

例如:

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"] })

但更好的方法是将每个位置字典解析为自定义对象并对这些自定义对象进行排序:

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