Saturday, May 27, 2017

How to Sort Array, Dictionary, and Array of Tuples

The code below shows how to sort an array, a dictionary or an array of tuples in Swift 3.1 with Xcode 8.3.1 Playground. Sorting can be done in ascending or descending order. A dictionary can be sorted by key or by value.

Note: When sorting a dictionary, the returned type is an array of tuples.

//Array
let array = [3, 5, 9, 7, 4, 1, 2]

let arrayInc = array.sorted()
let arrayDec = array.sorted(by: >)

//Dictionary
let dict = ["A": 123, "B": 789, "C": 567, "D": 432]

print(dict)

let dictKeyInc = dict.sorted(by: <)
let dictKeyDec = dict.sorted(by: >)

print(dictKeyInc)
print(dictKeyDec)

let dictValInc = dict.sorted(by: { $0.value < $1.value })
let dictValDec = dict.sorted(by: { $0.value > $1.value })

print(dictValInc)
print(dictValDec)

for item in dictValDec {
    print("key:\(item.key) value:\(item.value)")
}

//Array of Tuples
let tupleArray = [("A", 123), ("B", 789), ("C", 567), ("D", 432)]

let tupleArrayInc = tupleArray.sorted(by: { $0.1 < $1.1 })


print(tupleArrayInc)


Result:

["B": 789, "A": 123, "C": 567, "D": 432]
[(key: "A", value: 123), (key: "B", value: 789), (key: "C", value: 567), (key: "D", value: 432)]
[(key: "D", value: 432), (key: "C", value: 567), (key: "B", value: 789), (key: "A", value: 123)]
[(key: "A", value: 123), (key: "D", value: 432), (key: "C", value: 567), (key: "B", value: 789)]
[(key: "B", value: 789), (key: "C", value: 567), (key: "D", value: 432), (key: "A", value: 123)]
key:B value:789
key:C value:567
key:D value:432
key:A value:123
[("A", 123), ("D", 432), ("C", 567), ("B", 789)]

Reference

Sort Dictionary by Key Value
cannot assign value of type '[(string, string)]' to type '[string : string]'

No comments:

Post a Comment