I have an array of a struct and I would like to be able to sort it by either of the two variables using sort() if possible
struct{ var deadline = 0 var priority = 0 }
I looked at sort() in the documentation for the Swift programming language but it shows only simple arrays. can sort() be used or will I have to build my own?
To sort an integer array in increasing order in Swift, call sort() method on this array. sort() method sorts this array in place, and by default, in ascending order.
Sort functions bellow are exactly the same, the only difference how short and expressive they are:
Full declaration:
myArr.sort { (lhs: EntryStruct, rhs: EntryStruct) -> Bool in // you can have additional code here return lhs.deadline < rhs.deadline }
Shortened closure declaration:
myArr.sort { (lhs:EntryStruct, rhs:EntryStruct) in return lhs.deadline < rhs.deadline } // ... or even: myArr.sort { (lhs, rhs) in return lhs.deadline < rhs.deadline }
Compact closure declaration:
myArr.sort { $0.deadline < $1.deadline }
Full declaration:
let newArr = myArr.sorted { (lhs: EntryStruct, rhs: EntryStruct) -> Bool in // you can have additional code here return lhs.deadline < rhs.deadline }
Shortened closure declaration:
let newArr = myArr.sorted { (lhs:EntryStruct, rhs:EntryStruct) in return lhs.deadline < rhs.deadline } // ... or even: let newArr = myArr.sorted { (lhs, rhs) in return lhs.deadline < rhs.deadline }
Compact closure declaration:
let newArr = myArr.sorted { $0.deadline < $1.deadline }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With