Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you sort an array of structs in swift

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?

like image 826
DCorrigan Avatar asked Jul 16 '14 12:07

DCorrigan


People also ask

How do you sort an array in ascending order in Swift?

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.


1 Answers

Sort within the same array variable

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 } 

Sort to a new array variable

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 } 
like image 116
Keenle Avatar answered Sep 20 '22 02:09

Keenle