I'm trying to sort an NSArray of CGPoints (describing a CGPath) by their y values (descending), then by their x values (ascending). This is what I have so far (Swift code):
var anglePoints:[CGPoint] = [CGPoint(x: 0, y: 0), CGPoint(x: 32, y: 32), CGPoint(x: 32, y: 0)]
anglePoints.sort { $0.0.y > $0.1.y }
// anglePoints is now equal to [CGPoint(x: 32, y: 32), CGPoint(x: 32, y: 0), CGPoint(x: 0, y: 0)]
Obviously, sorting on x after this will result in the y values no longer being in order.
Is there a way to perform both sorts in a single call? Something like Linc's OrderBy().ThenBy()
?
You can do that with a single sort:
anglePoints.sort { $0.0.y != $0.1.y ? $0.0.y > $0.1.y : $0.0.x < $0.1.x }
which can be more explicitly written as:
anglePoints.sort {
if $0.0.y != $0.1.y {
return $0.0.y > $0.1.y
} else {
return $0.0.x < $0.1.x
}
}
Translated in words: if the y
coordinates are different, sort by y
, otherwise by x
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.