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]'
sorting for array of dictionaries in swift 3
ReplyDeleteHi, how can I return a dictionary from the sorted function?
ReplyDelete