如何对数组进行排序?对象如何以x的升序排列

时间:2022-01-21 16:44:58

I have an array of rectangle objects which I've populated in an array rectangles. Each rectangle has various properties, texture, position and so on. How can I sort the rectangles array so that the objects are arranged in ascending order of the x position. The x position property is accessible in the following way, for example.

我有一个矩形对象数组我在数组矩形中填充了这些对象。每个矩形都有不同的属性、纹理、位置等等。如何对矩形数组进行排序,使对象按x位置的升序排列。例如,可以通过以下方式访问x position属性。

rectangles[0].sprite.position.x

I am open to a solution to this problem that is faster or more effective than sorting.

我对这个问题的解决方案持开放态度,它比排序更快或更有效。

2 个解决方案

#1


3  

Use sort() method. let sortedRectangles = rectangles.sort {$0.sprite.position.x < $1.sprite.position.x}

使用sort()方法。让sortedRectangles =矩形。{ sprite.position 0.美元。x < 1.美元sprite.position.x }

#2


2  

rectangles is an array with range (x,y):

矩形是一个范围为(x,y)的数组:

    func backwardsX(s1: (CGFloat,CGFloat), _ s2:  (CGFloat,CGFloat)) -> Bool {
        return s1.0 > s2.0
    }
    let result    = rectangles.sort(backwardsX)

Even in one line:

即使在一行:

let result = rectangles.sort( { s1, s2 in return s1.0 > s2.0 } )

or

let result = rectangles.sort( { $0.0 > $1.0 } )

#1


3  

Use sort() method. let sortedRectangles = rectangles.sort {$0.sprite.position.x < $1.sprite.position.x}

使用sort()方法。让sortedRectangles =矩形。{ sprite.position 0.美元。x < 1.美元sprite.position.x }

#2


2  

rectangles is an array with range (x,y):

矩形是一个范围为(x,y)的数组:

    func backwardsX(s1: (CGFloat,CGFloat), _ s2:  (CGFloat,CGFloat)) -> Bool {
        return s1.0 > s2.0
    }
    let result    = rectangles.sort(backwardsX)

Even in one line:

即使在一行:

let result = rectangles.sort( { s1, s2 in return s1.0 > s2.0 } )

or

let result = rectangles.sort( { $0.0 > $1.0 } )