How to write a single extension for multiple types to override their Objective-C superclass' methods?

I have

import SpriteKit 

class SceneTypeA: SKScene {} // SKScene: SKNode
class SceneTypeB: SKNode  {} // Different inheritance paths.

extension SceneTypeA {
    override func mouseEntered(with event: NSEvent) {} // Works.
}

extension SceneTypeB {
    override func mouseEntered(with event: NSEvent) {} // Works.
}

But how to avoid code duplication? especially when I have multiple mouse/touch/keyboard methods for both types.

Things I've tried:

protocol MouseHandler {
    func mouseEntered(with event: NSEvent)
}
extension SKNode: MouseHandler {}

extension MouseHandler where Self == SKNode { // or Self: SKNode
    override func mouseEntered(with event: NSEvent) {
        // ❌ Method does not override any method from its superclass
    }
}
extension SKNode where Self: SKScene { // ❌ Trailing 'where' clause for extension of non-generic type 'SKNode'
    open override func mouseEntered(with event: NSEvent) {
        // ❌ Members of constrained extensions cannot be declared @objc
    }
}

If I create a subclass of SKNode, it won't apply to subclasses of SKScene: SKNode.

1 Like
Terms of Service

Privacy Policy

Cookie Policy