【问题标题】:How can I sort all elements in a complex set of GKEntity?如何对一组复杂的 GKEntity 中的所有元素进行排序?
【发布时间】:2021-01-25 02:17:05
【问题描述】:

我有 4 个类,如D_Entity,P_Entity,T_Entity and O_Entity,定义如下:

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!
     .............
} 

是的,所有四个类都有 S_Comp 的相同成员,其派生如下:

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

然后,我将D_Entity,P_Entity,T_Entity and O_Entity的所有对象插入到一个名为entities的变量中,定义为:

var entities = Set <GKEntity>()

问题是:我想按S_Comp's position.y. 的顺序对entities 中的所有元素进行排序(S_Comp 派生自GKComponent,它具有position 的成员)。在 Swift 2 中,示例显示:

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
}

然而,在 Swift4 或 5 中,Xcode 报错:

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

我还发现GKEntity中有一个函数叫sorted,但是我不知道怎么在这么复杂的集合中使用它。

有人知道怎么解决吗?

非常感谢。

【问题讨论】:

  • sortsorted 的工作方式几乎相同。唯一的区别是sort 返回Void 并就地编辑集合,而sorted 返回一个已排序的新副本,保持原样不变。

标签: ios swift sorting set gameplay-kit


【解决方案1】:

在 Swift 5 Set 中没有排序功能

所以,你可以像这样使用 Sorted 函数:

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
})

【讨论】:

    猜你喜欢
    • 2019-09-02
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多