2

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()?

MassivePenguin
  • 3,701
  • 4
  • 24
  • 46

1 Answers1

1

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

Antonio
  • 71,651
  • 11
  • 148
  • 165