在 GameplayKit 中,我想遵循 GKAgentDelegate 协议(protocol),因此使用委托(delegate)方法 func agentDidUpdate(agent: GKAgent)
。
问题是,在这个方法中,参数agent被声明为GKAgent,而不是GKAgent2D,所以我无法访问agent.position
,因为position属性在GKAgent2D中,而不是GKAgent中。 .
但是在 Objective-C API 中,代理被声明为 GKAgent2D。
请帮忙。
最佳答案
由于 GKAgent2D
是 GKAgent
的子类,因此您可以简单地向上转换它:
func agentDidUpdate(agent: GKAgent) {
if let agent2d = agent as? GKAgent2D {
// do thing with agent2d.position
}
}
GKAgentDelegate
的文档(来自 Xcode 7,beta 1;即 OSX 10.11 SDK)显示了两种语言的相同类型 (GKAgent
):
因此,为了严格正确,在 Objective-C 下它应该一直是 GKAgent
,但是 Objective-C 的类型安全性不如 Swift,所以你可以摆脱它(使用如果将 GKAgent
对象传递给委托(delegate)方法并且您假设它是 GKAgent2D
,您可能会遇到 无法识别的选择器
异常) .
关于swift - Swift 中 GKAgentDelegate 的协议(protocol)方法不对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30885544/