Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failable initializer in Xcode 6.1

Tags:

xcode

ios

swift

I have a custom UITableViewCel (nothing fancy) that works perfectly on Xcode 6.0. When I try to compile it with Xcode 6.1 the compiler shows the following error:

A non-failable initializer cannot chain to failable initializer 'init(style:reuseIdentifier:)' written with 'init?'

Here is the code of the cell:

class MainTableViewCell: UITableViewCell {

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.setup()
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.setup()
    }

    func setup() {<...>}
}

As a solution the compiler proposes Propagate the failure with 'init?':

override init?(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    self.setup()
}

I'm a bit confused. Is it possible to elaborate what is a (non)failable initialiser and how it should be used and overrided?

like image 410
Artem Abramov Avatar asked Oct 17 '14 14:10

Artem Abramov


1 Answers

With Swift 1.1 (in Xcode 6.1) Apple introduced failable initializers -- that is, initializers that can return nil instead of an instance. You define a failable initializer by putting a ? after the init. The initializer you're trying to override changed its signature between Xcode 6.0 and 6.1:

// Xcode 6.0
init(style: UITableViewCellStyle, reuseIdentifier: String?)

// Xcode 6.1
init?(style: UITableViewCellStyle, reuseIdentifier: String?)

So to override you'll need to make the same change to your initializer, and make sure to handle the nil case (by assigning to an optional) when creating a cell that way.

You can read more about failable initializers in Apple's documentation.

like image 55
Nate Cook Avatar answered Sep 18 '22 23:09

Nate Cook