Aeradriel
Aeradriel

Reputation: 1232

Changes on NSCoding protocol

I just came back on the development of a Swift application for iOs that I started back on August. It seems that a lot of changes happened. Now my NSCoding protocol is not valid anymore and I cannot find what's wrong. Actually I do but I don't know how to implement my old code with the new protocol. Here is my old init(coder: NSCoder) :

required init(coder: NSCoder!) {
    if (coder != nil) {
        //Variables initialization
    }
    else {
        //Defaults values
    }
    super.init()
}

Actually, I cannot use NSCoder! anymore so I cannot check if there is a coder so if I have to set default values or not. The question is : When coder is nil, what initializer is called ? Is it init or init(coder: NSCoder!) ? If it's the second one, how to do what I use to do (with the code above) ?

Upvotes: 2

Views: 130

Answers (1)

Brian Nickel
Brian Nickel

Reputation: 27550

With the updated protocol it is illegal for a Swift class implementing NSCoding to receive nil in initWithCoder. This should simplify your code since a nil coder is an exceptional case and the program should have taken an alternative path when it couldn't create the decoder.

If you really have two paths you can break your init into two methods:

override init() {
    //Variables initialization
    super.init()
}

required init(coder: NSCoder) {
    //Defaults values
    super.init()
}

This does have implications for Objective-C code consuming this class since passing nil will crash the app. Swift code will be safe since it will generate a compilation error is you pass an optional.

Upvotes: 2

Related Questions