0

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.

Swift Dev Journal
  • 19,282
  • 4
  • 56
  • 66
Wang Ying
  • 25
  • 4
  • `sort` and `sorted` work almost identically. The only difference is that `sort` returns `Void` and edits the set in-place, whereas `sorted` returned a new copy that has been sorted, keeping the original intact. – Alexander Jan 25 '21 at 02:43

1 Answers1

1

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
})
Jignesh Mayani
  • 6,937
  • 1
  • 20
  • 36