33

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?

1

2 Answers 2

71

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 }
Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.