2016-07-14 53 views
-4

我有字典的一個數組,如下所示:如何排序字典的數組

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

我想排序經度。

回答

1

例如:

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