将字典字典排序为字典

时间:2015-10-02 14:31:01

标签: sorting dictionary swift2

我正在尝试使用Swift 2对包含大量词典的词典进行排序。

var dicListItems: [String: [String: AnyObject]] = [
    "Micke": ["LastName": "Andrius", "Age": 41],
    "Brian": ["LastName": "Zini", "Age": 35],
    "Frank": ["LastName": "Kramer", "Age": 28],
    "Derek": ["LastName": "Allen", "Age": 25]
]

我想以某种不同的方式排序:

1)来自姓氏:

[
    "Derek": ["LastName": "Allen", "Age": 25],
    "Micke": ["LastName": "Andrius", "Age": 41],
    "Frank": ["LastName": "Kramer", "Age": 28],
    "Brian": ["LastName": "Zini", "Age": 35]
]

2)来自FirstName:

[
    "Brian": ["LastName": "Zini", "Age": 35],
    "Derek": ["LastName": "Allen", "Age": 25],
    "Frank": ["LastName": "Kramer", "Age": 28],
    "Micke": ["LastName": "Andrius", "Age": 41]
]

3)从年龄:

[
    "Derek": ["LastName": "Allen", "Age": 25],
    "Brian": ["LastName": "Zini", "Age": 35],
    "Frank": ["LastName": "Kramer", "Age": 28],
    "Micke": ["LastName": "Andrius", "Age": 41]
]

2 个答案:

答案 0 :(得分:1)

您的情况有些问题:

我想你可以把你的数据转换成这种东西(它是一个可以排序的数组):

var dicListItems: [[String : AnyObject]] = [
["FirstName" :"Micke", "LastName": "Andrius", "Age": 41],
["FirstName" : "Brian", "LastName": "Zini", "Age": 35],
["FirstName" : "Frank", "LastName": "Kramer", "Age": 28],
["FirstName" : "Derek", "LastName": "Allen", "Age": 25]
]

然后你可以使用swift的.sort函数来对你的数组进行排序。例如,这是FirstName的排序:

let dictListItems: [[String : AnyObject]] = [["FirstName" :"Micke", "LastName": "Andrius", "Age": 41],     ["FirstName" : "Brian", "LastName": "Zini", "Age": 35], ["FirstName" : "Frank", "LastName": "Kramer", "Age": 28], ["FirstName" : "Derek", "LastName": "Allen", "Age": 25]]

let sortedList = dictListItems.sort {
        item1, item2 in
        let firstName1 = item1["FirstName"] as! String
        let firstName2 = item2["FirstName"] as! String
        return firstName1.compare(firstName2) != NSComparisonResult.OrderedAscending
    }

答案 1 :(得分:0)

第一个问题,它是Objective-C,而不是Swift。 第二:你不能对Dictionary进行排序,你应该使用Array。 Swift 2中的解决方案如下:

var listItems = [
    ["FirstName": "Micke", "LastName": "Andrius", "Age": 41],
    ["FirstName": "Brian", "LastName": "Zini", "Age": 35],
    ["FirstName": "Frank", "LastName": "Kramer", "Age": 28],
    ["FirstName": "Derek", "LastName": "Allen", "Age": 25]
]
listItems.sortInPlace( { ($0["FirstName"] as! String) < ($1["FirstName"] as! String)} )
print(listItems)

显然你可以在排序条件下更改密钥。