简体   繁体   English

Swift:按一个值对CGPoints的NSArray排序,然后对另一个值排序?

[英]Swift: Sort NSArray of CGPoints by one value, then another?

I'm trying to sort an NSArray of CGPoints (describing a CGPath) by their y values (descending), then by their x values (ascending). 我试图按其y值(降序),然后按其x值(升序)对CGPoints的NSArray(描述CGPath)进行排序。 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. 显然,在此之后对x进行排序将导致y值不再按顺序排列。

Is there a way to perform both sorts in a single call? 有没有办法在单个调用中执行两种排序? Something like Linc's OrderBy().ThenBy() ? 像Linc的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 翻译成单词:如果y坐标不同,则按y排序,否则按x排序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM