1

Any idea on how to sort an array of SKShapeNode elements by their names? Let just assume each SKShapeNode.name property is a number 100,23,31,... All of them are group into shapeNodesCollection. What should be done to sort it out into another array - shapeNodesCollectionSorted? Below you can find some abstract code.

class Example: GameScene {

    ...

    var shapeNodesCollection = [SKShapeNode]()
    var shapeNodesCollectionSorted = [SKShapeNode]()

    ...

    shapeNodesCollectionSorted = ... //sorted shapeNodesCollection

}

Many thanks to anyone for any contribution.

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
RafalK
  • 749
  • 2
  • 7
  • 13
  • https://stackoverflow.com/questions/24130026/swift-how-to-sort-array-of-custom-objects-by-property-value, https://stackoverflow.com/questions/27337495/sort-a-skspritenode-array-according-to-a-specific-element – Martin R Jul 06 '17 at 15:04
  • @Matrin R, much appreciated – RafalK Jul 06 '17 at 15:31

1 Answers1

3

If the name property is a simple numeric type (e.g., Int, Float, etc) then this should be enough:

var shapeNodesCollectionSorted = shapeNodesCollection.sorted { $0.name < $1.name }

The shapeNodesCollectionSorted will then contain the shapes sorted in ascending order according to the name property.

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85