1

I have created a subclass of NSView as seen below

class StudentCardView: NSView {
    let firstName: String

    init(name: String) {
        firstName = name
        super.init()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder) <-- ERROR: firstName not initialised
    }
}

let myName = "Test-Name"
var cell = StudentCardView(name: myName)

How do I get rid of an error which requires firstName to be initialized in init(coder) as I don't intend to make any views of StudentCardView in the storyboard.

I agree, one is required to initialize all the constants before the superclass initializer is called. Is there a way out here? Have I made any design mistakes?

0

1 Answer 1

2

It is very annoying that the init?(coder:NSCoder) initializer is mandatory because often you do not need it. Let's hope this changes in a future Cocoa release.

But there is hope. When Xcode tells you that you need that initializer, it actually gives you the option to include a simple version from a built-in template. It looks like this:

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

The interesting thing to note here is the fatalError(). That actually also silences the error that you are asking about. That happens because that function is marked with the @noreturn annotation, which the compiler takes as a hint that it can stop doing checks because no code after the fatalError() will ever execute.

So you can keep your nice strict non-mutable let instance variables :-)

Sign up to request clarification or add additional context in comments.

5 Comments

The better way to think of it is that it is implemented and explicitly crashes rather than quietly doing the wrong thing as in ObjC. You always need something here because while you may not intend views to be loaded from a nib, they are permitted to, and Swift tries to cover what is possible, not just what is expected. (After all, bugs are almost always due to things that "should not" happen but actually do happen.)
@RobNapier do you know if the compiler treats fatalError in some special way?
Absolutely. It includes the attribute @noreturn, which tells the compiler that the call will not return, so everything else is irrelevant.
Ah I did not know about @noreturn! That was the missing piece of this puzzle :-)
I don't understand. In my subclass of NSView this initializer get's called and hence my app crashes immediately. My other initializer required init(frameRect: NSRect) {} is not called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.