swift - Swift 子类方法未被识别
问题描述
我正在使用 SpriteKit,并且我有一个为 SKSpriteNode 类编写的子类。
class PlayFieldNode: SKSpriteNode {
var myFunction: (()->())?
// other methods
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?){
if let f = myFunction {
f()
}
}
}
在我想做的 PlayFieldNode 的子节点内,
self.parent!.myFunction = self.myFunction
当我尝试这样做时,它甚至不会编译,并且会发出警告,例如,Value of type 'SKNode' has no member 'myFunction'
我对使用 swift 比较陌生,我是否遗漏了一些涉及继承或闭包的东西?我已经仔细检查并确保父级实际上是我想要使用的 PlayFieldNode。
解决方案
是的,因为 parent 是基SKNode
类,它对你的一无所知myFunction
,所以你首先需要检测 parent是否是你的子类,所以使用
if let parent = self.parent as? PlayFieldNode {
parent.myFunction = self.myFunction
}
推荐阅读
- javascript - 尽管关注了有关主题的所有堆栈溢出文章,但无法将 Electron 初始化为 Angular 项目,反之亦然
- asp.net - 在 Web 窗体应用程序中实现 Azure ADFS
- python - 使用 Selenium 和 for 循环抓取多个页面
- reactjs - React 17 在函数返回中使用条件开关
- keystore - KeyStore.setKeyEntry 在 FIPS 模式下不起作用
- go - 使用反射和不安全包复制切片
- java - 如何通过代码知道是否有多个显示器连接到我的系统?
- python - TypeError:“MongoClient”对象不可调用
- javascript - 如何避免在 react.js 中按下按钮时打开所有弹出窗口?
- gradle - Gradle 中依赖项的版本范围并锁定 CI 构建的特定版本