I am trying to sort an array of structure depending on its property.
Lets say I want to sort an array of NSViews
by the x coordinate.
How can I achive this?
I am trying to sort an array of structure depending on its property.
Lets say I want to sort an array of NSViews
by the x coordinate.
How can I achive this?
Its a very pretty solution for that, and its called Closure Expression Syntax.
What you need to do is:
let sortedArray = sorted(allViewsArray, { (p1: NSView, p2: NSView) -> Bool in
return p1.frame.origin.x < p2.frame.origin.x
})
This will sort the alLViewsArray
from the biggest X coordinate to the smallest, and store it in sortedArary
.
Note, you can simplify the syntax a little, which often helps with readability (focus is on what you’re doing rather than the syntax of the types etc):
let sortedArray = sorted(allViewsArray) {
$0.frame.origin.x < $1.frame.origin.x
}
Trailing closures can be outside the function call parens, resembling other block structures like if
or while
; you can skip the return
if the closure expression is a single statement, and you can skip the function signature and use $0
, $1
etc. for the argument names.
That last one is best used only when there are no more useful names to be had (e.g. p1
is no more descriptive than $0
). If you do want to give them names, you can still skip the types:
let sortedArray = sorted(allViewsArray) { p1, p2 in
p1.frame.origin.x < p2.frame.origin.x
}
Swift is sometimes a little fragile when applying this syntax sugar so occasionally you’ll find it can’t be shortened quite as much as it ought, but it usually works.