[Solved] How to convert Array to Dictionary while keeping the same order Swift


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

solved How to convert Array to Dictionary while keeping the same order Swift