swift - Swift 中 GKAgentDelegate 的协议(protocol)方法不对?

标签 swift sprite-kit ios9 gameplay-kit

在 GameplayKit 中,我想遵循 GKAgentDelegate 协议(protocol),因此使用委托(delegate)方法 func agentDidUpdate(agent: GKAgent)

问题是,在这个方法中,参数agent被声明为GKAgent,而不是GKAgent2D,所以我无法访问agent.position,因为position属性在GKAgent2D中,而不是GKAgent中。 .

但是在 Objective-C API 中,代理被声明为 GKAgent2D。

请帮忙。

最佳答案

由于 GKAgent2DGKAgent 的子类,因此您可以简单地向上转换它:

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

enter image description here

因此,为了严格正确,在 Objective-C 下它应该一直是 GKAgent,但是 Objective-C 的类型安全性不如 Swift,所以你可以摆脱它(使用如果将 GKAgent 对象传递给委托(delegate)方法并且您假设它是 GKAgent2D,您可能会遇到 无法识别的选择器 异常) .

关于swift - Swift 中 GKAgentDelegate 的协议(protocol)方法不对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30885544/

相关文章:

MagicalRecord saveWithBlock 的 Swift 语法

ios - NSMutableParagraphStyle : Some properties not working on iOS 10. 3.2 和 10.3.3

ios - UICollectionView 单元格在删除具有 estimatedItemSize 的项目时调整大小

ios - 如何检查 SpriteKit 中屏幕的两半是否有触摸?

ios - AdMob Interstitial 每五场比赛一次

swift - 迭代类型数组时出现 "Use of undeclared type "错误

ios - 引用/更改节点的大小(在调用它之后)

security - 处理应用程序传输安全(kCFStreamErrorDomainSSL,-9802)

ios - dyld : Library not loaded: @rpath/Alamofire. 设备 iOS 9 上的框架/Alamofire 错误,无法编译

iOS 9 : KVO no longer working