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?

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 }

Need Your Help

In ggplot2, what do the end of the boxplot lines represent?

r ggplot2 boxplot

I can't find a description of what the end points of the lines of a boxplot represent.

Execute managebean method from javascript onload event

java javascript jsf jsf-2

How can I make an ajax request that updates a &lt;h:dataTable&gt; from javascript? I am currently loading the initial data using @Postconstruct but that is significantly delaying the initial page l...