iosswiftinitializationawakefromnib

Why should we use init(coder) when we can just dump everything inside awakeFromNib?


I read What exactly is init coder aDecoder?

but that doesn't answer to why not put everything inside awakeFromNib and forget using init(coder aCoder : NSCoder)?

In the comments of the accepted answer Fattie says:

"sometimes you can't do that". You typically can but not always

Can anyone provide more explanation to that?


Solution

  • If you have lets that need to be initialized in an init, you have to use that instead of awakeFromNib.

    Doing so allows you to avoid implicitly unwrapped optionals.

    EDIT:

    If you want your class to have properties, you can either do

     let a: String
    

    or

     var a: String! = nil // this is called an "implicitly unwrapped optional" -- it's the ! at the end of the type that makes it that.
    

    The first is preferable because it is safe. In the second, you run the risk of accessing a before it is initialized.

    But, to make sure a is always initialized, it needs to get its value in an init of the class.

    So,

    init(coder aCoder : NSCoder) {
       a = "hello" // usually this is something more complex
       // read in coder or whatever else you need to do
    }
    

    If you don't have an init, then you can't have an init that gets initialized later.