Search code examples
swiftdictionaryswap

how to swap items in Dictionary


I have Dictionary like this

let test = ["first":1,"second":2,"third":3]

I want to swap first item to the third item like this

let test = ["third":3,"second":2,"first":1]

how can I swap item?


Solution

  • Dictionaries in Swift are an unordered collection type. The order in which the values will be returned cannot be determined.

    You can use sorted(by:) method to sort the dictionaries. The result type will be array of tuples.

    let test = ["first":1,"second":2,"third":3]
    //let result = test.sorted { $0.key > $1.key }
    let result = test.sorted { item1, item2 in
        return item1.key > item2.key
    }
    print(result)//[(key: "third", value: 3), (key: "second", value: 2), (key: "first", value: 1)]