首页 > 解决方案 > 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。

标签: swiftsprite-kit

解决方案


是的,因为 parent 是基SKNode类,它对你的一无所知myFunction,所以你首先需要检测 parent是否是你的子类,所以使用

if let parent = self.parent as? PlayFieldNode {
   parent.myFunction = self.myFunction
}

推荐阅读