Crashalot Crashalot - 6 months ago 48
Swift Question

Swift: "Must call a designated initializer of the superclass" error even though code is doing so

The goal is to subclass SCNNode. According to the class docs,

init(geometry geometry: SCNGeometry?)
is a designated initializer (no
keyword listed), so isn't this code invoking a designated initializer of its superclass?

Why is Xcode showing the following error?

Must call a designated initializer of the superclass SCNNode

class PreviewNode: SCNNode {
// Constants
let PreviewNodeColor = gRedColor
let Size = CGFloat(1.0)
let ChamferRadius = CGFloat(0.0)

override init() {
let previewBox = SCNBox(width: Size, height: Size, length: Size, chamferRadius: ChamferRadius)
previewBox.firstMaterial!.diffuse.contents = PreviewNodeColor
previewBox.firstMaterial!.transparency = 0.2
previewBox.firstMaterial!.specular.contents = UIColor.whiteColor()
super.init(geometry: previewBox)


The problem there is that you are also trying to access your PreviewNode properties before calling self.init()

Try like this:

Xcode 8 GM • Swift 3

class PreviewNode: SCNNode {
    let previewNodeColor: UIColor = .red
    let size: CGFloat = 1
    let chamferRadius: CGFloat = 0
    convenience override init() {
        let previewBox = SCNBox(width: size, height: size, length: size, chamferRadius: chamferRadius)
        previewBox.firstMaterial?.diffuse.contents = previewNodeColor
        previewBox.firstMaterial?.transparency = 0.2
        previewBox.firstMaterial?.specular.contents = UIColor.white
        self.geometry = previewBox