Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly set true Bool is somehow set to false

Tags:

swift

Do the following:

Create a class called A, subclass of UITableViewCell:

class A: UITableViewCell {
    var isChosen: Bool = true
}

Create a xib file and drag a UITableViewCell object as the top level object, and make sure to set its class to A:

enter image description hereenter image description here

Create an instance of A:

var a = NSBundle.mainBundle().loadNibNamed("A", owner: nil, options: nil)[0] as A

Print isChosen:

println(a.isChosen)

Output:

false

Why is this happening? It only happens when you initialize the instance from a nib.

Even if you declare the variable as an optional and set it to nil:

var isChosen: Bool! = nil

it'll still be set to false somehow.

like image 457
Snowman Avatar asked Aug 01 '14 19:08

Snowman


1 Answers

Since your class A does not have any init methods defined swift automatically generated default initializer for you. With default init() method code var isChosen: Bool = true is a shortcut to:

class A: UITableViewCell {
    var isChosen: Bool

    init() {
        isChosen = true
    }
}

When you create your custom cell of type A from Nib then auto generated init() method does not get called because initWithCoder called hence isChosen value is false.


UPDATE:

As already mentioned by @MattGibson in comments to the question, with xCode 6 Beta 5 update we can address the problem. It can be solved by adding init with coder initializer and marking it as required, so A should contain code bellow:

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

How it works? From Beta 5 Release Notes:

The required modifier is written before every subclass implementation of a required initializer. Required initializers can be satisfied by automatically inherited initializers.

UPDATE:

required init(coder aDecoder: NSCoder!) { ... } should be added only if you override at lest one init method in your class.

like image 132
Keenle Avatar answered Oct 17 '22 07:10

Keenle