我是cocos2d开发人员,目前我们正在开发Swift端口。我遇到了一个非常奇怪的问题,我怀疑它是一个Swift编译器错误,但也许它仍然是我。
我有以下代码
public protocol Tagged {
var tag: Int { get set }
}
public protocol Component: Tagged {
weak var owner: Node? { get /*set*/}
func onAdd(to owner: Node)
func onRemove()
}
open class ComponentBase: Component {
public weak var owner: Node?
open var tag: Int = 0
open func onAdd(to owner: Node) {
self.owner = owner
}
open func onRemove() {
self.owner = nil
}
}
public protocol FixedUpdatable: class, Prioritized {
func fixedUpdate(delta: Time)
}
open class CustomComponent: ComponentBase, FixedUpdatable {
}
open class Node: Responder {
// MARK: Components
/// Array of components added to the node
internal(set) public var components = [Component]()
internal var fixedUpdatableComponents = [FixedUpdatable & Tagged]()
public func add(component: Component) -> Bool {
...
components.append(component)
component.onAdd(to: self)
...
if let c = component as? FixedUpdatable & Tagged {
// TODO: Insert with priority in mind
fixedUpdatableComponents.append(c)
// If it is first component
if isInActiveScene && fixedUpdatableComponents.count == 1 {
scene.scheduler.schedule(fixedUpdatable: self)
}
}
}
}
extension Node: FixedUpdatable {
public final func fixedUpdate(delta: Time) {
fixedUpdatableComponents.forEach { $0.fixedUpdate(delta: delta) }
}
}
//然后在调度程序中我有
for t in self.fixedUpdatableTargets {
t.fixedUpdate(delta: timer.repeatInterval)
}
它在迭代期间崩溃,更准确地说是在执行第一个闭包期间。
我应该向Apple团队提交错误吗?我尝试了很多东西,但没有一个工作(在闭包中再次重新设置对象,在很多方面覆盖标记属性)。
更新 这有效:
for c in fixedUpdatableComponents as [FixedUpdatable] {
c.fixedUpdate(delta: delta)
}
这不是:
fixedUpdatableComponents.forEach { $0.fixedUpdate(delta: delta) }
fixedUpdatableComponents.forEach { let c = $0 as FixedUpdatable; c.fixedUpdate(delta: delta) }
for c in fixedUpdatableComponents { c.fixedUpdate(delta: delta) }
for c: FixedUpdatable in fixedUpdatableComponents { c.fixedUpdate(delta: delta) }
请注意fixedUpdatableComponents
为[FixedUpdatable & Tagged]