In Swift, a Dictionary
is an unordered collection by design. Therefore you can't keep any order to it after migrating from an Array
.
If you want your values to be nil
, just use
let dict = Dictionary<Int, Any?>(uniqueKeysWithValues: [1, 2, 3].map { ($0, nil) })
This evaluates to [2: nil, 3: nil, 1: nil]
If you want some sort of sorting (no pun intended), you may convert the dict to a sorted tuple array:
let sortedTupleArray = dict.sorted { $0.key > $1.key }
This evaluates to [(key: 3, value: nil), (key: 2, value: nil), (key: 1, value: nil)]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…