Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending SCNNode in Swift

Tags:

swift

scenekit

I would like to extend SCNNode (if possible) in Swift. Here's my attempt:

class MyNode : SCNNode {

    override init(geometry: SCNGeometry) -> SCNNode {
        return super.init(geometry)
    }

    /* Xcode required this */
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

The -> operator is being tagged with an error "Consecutive declarations on a line must be separated by ;".

I know this is not right but if I humour Xcode it "fixes" it as follows:

override init(geometry: SCNGeometry); -> SCNNode {

Which is nonsense and then Xcode complains "Expected declaration".

I don't quite understand the SCNNode implementation - if I look at it in Xcode it's all declared as abstract (in comments) and offers no implementation. The docs do not suggest anything extends from SCNNode, you instantiate it directly, so I am assuming I should be able to extend it.

like image 417
PorridgeBear Avatar asked Feb 12 '23 03:02

PorridgeBear


1 Answers

You can simply do:

class MyNode : SCNNode {
    /* Xcode required this */
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

Which will inherit the designated initialiser from the base class.

If you want to specify your own initialiser that takes a geometry, you must call a designated initialiser of the base class, so I'd say this would be what you'd want:

class MyNode : SCNNode {
    init(geometry: SCNGeometry) {
        super.init()
        self.geometry = geometry
    }
    /* Xcode required this */
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

The initialiser you're seeing in the SCNNode.h code is an initialiser translated (automatically, I believe) from the Objective C method nodeWithGeometry. I believe this is a convenience initialiser, even though it's not specifically marked as such, which I'd personally say is a bug/limitation of the automatic header file translation. The documentation specifically says:

For consistency and simplicity, Objective-C factory methods get mapped as convenience initializers in Swift.

Don't be confused by the word abstract in the comments; this is the HeaderDoc tag for a short description of a method, i.e. "abstract" is used in the sense of an abridgement or summary.

like image 60
Matt Gibson Avatar answered Feb 13 '23 20:02

Matt Gibson