How do you sort an array of structs in swift

Solutions Collect From Internet About “How do you sort an array of structs in swift”

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 }