简体   繁体   中英

ByPass init(coder) in NSView subclass

I am creating a subclass of NSView.
Following is my code from playground

class MyTableCell :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 = MyTableCell(name: myName)

How do I get rid of error which requires firstName to initialised in init(coder).
I wont be making any views of type MyTableCell from IB.

(I agree as per swift design, one is required to initialise all the constants before super class initialiser is called. But is there any way out here ? Have I made any design mistake ?)

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 :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM