Search code examples
iosswiftsortingsetgameplay-kit

How can I sort all elements in a complex set of GKEntity?


I have 4 classes like D_Entity,P_Entity,T_Entity and O_Entity,which have been defined as follows:

class D_Entity : GKEntity {
     var S_Comp : S_Component!
     .............
} 
class P_Entity : GKEntity {
     var S_Comp : S_Component!
     .............
} 
class T_Entity : GKEntity {
     var S_Comp : S_Component!
     .............
} 
class O_Entity : GKEntity {
     var S_Comp : S_Component!
     .............
} 

Yes, all the four classes have the same member of S_Comp, which derives like:

    class S_Component : GKComponent {
     .............
    } 

Then, I inserted all objects of D_Entity,P_Entity,T_Entity and O_Entity into a variable named entities, which is defined as:

var entities = Set <GKEntity>()

The problem is : I want to sort all elements in entities by the order of S_Comp's position.y. (S_Comp derives from GKComponent that has a member of position). In Swift 2, the example shows:

let ySortedEntities = entities.sort {
  let nodeA = $0.0.componentForClass(S_Component.self)!.node
  let nodeB = $0.1.componentForClass(S_Component.self)!.node
  return nodeA.position.y > nodeB.position.y
}

however, in Swift4 or 5, Xcode reported there is an error:

Value of type 'Set<GKEntity>' has no member 'sort'

I also found there is a function named sorted in GKEntity, but I don't know how to use it in such complex set.

Anyone knows how to solve it?

Thanks a lot in advance.


Solution

  • In Swift 5 Set has no sort function

    So, You can use Sorted function like this:

    let ySortedEntities = entities.sorted(by: {
         let nodeA = $0.0.componentForClass(S_Component.self)!.node
         let nodeB = $0.1.componentForClass(S_Component.self)!.node
         return nodeA.position.y > nodeB.position.y
    })