Reputation: 666
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?
Upvotes: 32
Views: 20751
Reputation: 5115
If you need to sort by comparable properties check if SortComparator
protocol can make it simpler for you. Available (macOS 12+, iOS 15+).
struct Task {
static var samples: [Self] = (0...5).map{ _ in .init() }
var deadline = Int.random(in: 0...20)
var priority = Int.random(in: 0...20)
}
Task.samples.sort(using: [
KeyPathComparator(\.deadline, order: .forward),
KeyPathComparator(\.priority, order: .reverse),
])
print(Task.samples)
Upvotes: 2
Reputation: 12190
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 }
Upvotes: 69