按原始顺序获取数组中的Dictionary键

时间:2016-08-13 04:04:30

标签: ios swift dictionary

我们说我有一本字典

let dict = [
    "Joe":"D.",
    "Ben":"K.",
    "Kyle":"R.",
    "Matt":"L."
]

如果我想要这个词典的数组,我会这样做:

let keys = Array(dict.keys)

但是这会以看似随机的顺序打印出来:

["Ben", "Joe", "Matt", "Kyle"]

有没有办法获得与原始字典具有相同顺序的键数组?

["Joe", "Ben", "Kyle", "Matt"]

1 个答案:

答案 0 :(得分:2)

字典没有订单。当我们向字典中添加新元素时,我们现在不接受订单。您可以使用元组数组

        let array = [("Joe", "D."), ("Ben", "K."), ("Kyle", "R.")]
        print(array)
//        [("Joe", "D."), ("Ben", "K."), ("Kyle", "R.")]
        let keys = array.map { $0.0 }
        print(keys)
//        ["Joe", "Ben", "Kyle"]