0

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?

Community
  • 1
  • 1
Honey
  • 24,125
  • 14
  • 123
  • 212

1 Answers1

1

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.

Lou Franco
  • 83,503
  • 14
  • 127
  • 183
  • You're answer is still a little too dense for me. Can you elaborate a bit more or add code? – Honey Mar 30 '17 at 17:49
  • Correct me if I'm wrong. Reading from [Why optional constant does **not** automatically have a default value of `nil`](http://stackoverflow.com/a/37400372/5175709)... I guess you mean if we *pass* the point of initialization then the properties that were constant will get *set* to `nil` and can no longer get out of that state...basically making that property useless. (I wrote this just at the moment you made your edit) – Honey Mar 30 '17 at 18:05
  • The workaround to that issue is making it `var` which is not great of the property really is a constant and you just didn't initialize it in an init. If it really changes a lot, a var (regular) optional is fine (not implicitly unwrapped) – Lou Franco Mar 30 '17 at 18:07
  • Thank you for the edit. 1. Is my previous comment related/correct? 2. won't `var a: String!` suffice as an "implicitly unwrapped optional"...I mean that would also set it to `nil` – Honey Mar 30 '17 at 18:11
  • 1
    Yes, it is correct. And, yes, anything declared with Type! is implicitly unwrapped, which we would like to avoid. We cannot avoid them in IBOutlets for ViewController (because they are set in viewDidLoad, not an init) -- your question is related to that problem in VCs. If there were an init that took an NSCoder, then we could set the outlets in it and they could be not declared with ! – Lou Franco Mar 30 '17 at 18:58