Swift:对字典数组中的键值对进行排序

时间:2017-05-01 23:16:26

标签: arrays swift sorting dictionary

我必须为我的第一个项目(在线课程)排序一系列的dictinaries。排序尚未涵盖,我自己也做了一些研究。去了Apple并阅读了有关闭包的内容,看了youtube以了解排序的概念,但我仍然对如何为此设置逻辑感到困惑(我假设是func)

这是我到目前为止的收藏品

var players: [[String: Any]] = [

        ["Name": "Joe Smith",
        "Height": 42,
        "Experience": true,
        "Guardians": "Jime and Jan Smith",
        "Team": ""],

        ["Name": "Jill Tanner",
        "Height": 36,
        "Experience": true,
        "Guardians": "Clara Tanner",
        "Team": ""],

        ["Name": "Bill Bon",
        "Height": 43,
        "Experience": true,
        "Guardians": "Sara and Jenny Bon",
        "Team": ""],
]

任何提示或来源都将非常感谢!

1 个答案:

答案 0 :(得分:0)

我强烈建议您将数据转换为结构数组(或可能是对象),而不是字典数组。使用Dictionary所需的弱类型(即将Any作为值的类型)使得词典真的很烦人。此外,在使用词典时,您在性能和安全方面也受到了巨大的打击。

struct Player {
    let name: String
    let height: Int
    let experience: Bool
    let guardians: String
    let team: String?
}

let players = [
    Player(
        name: "Joe Smith",
        height: 42,
        experience: true,
        guardians: "Jime and Jan Smith",
        team: nil
    ),
    Player(
        name: "Jill Tanner",
        height: 36,
        experience: true,
        guardians: "Clara Tanner",
        team: nil
    ),
    Player(
        name: "Bill Bon",
        height: 43,
        experience: true,
        guardians: "Sara and Jenny Bon",
        team: nil
    ),
]

// Example, sort by height

let sortedPlayers = players.sorted{ $0.height < $1.height }

for player in sortedPlayers {
    print(player)
}

我提供了sorted Array一个闭包的方法,告诉它如何在任何两个给定元素之间进行比较。在这个例子中,我写了一个关闭,将较短的玩家放在较高的玩家之前。