30

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?

DCorrigan
  • 646
  • 1
  • 8
  • 18
  • possible duplicate of [Swift how to sort array of custom objects by property value](http://stackoverflow.com/questions/24130026/swift-how-to-sort-array-of-custom-objects-by-property-value) – Martin R Jul 16 '14 at 12:47

2 Answers2

68

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 }
Keenle
  • 12,010
  • 3
  • 37
  • 46
0

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)
Paul B
  • 3,989
  • 33
  • 46