Vah.Sah Vah.Sah - 1 month ago 16
Swift Question

UISwitch. Segmentation fault: 11 with swift

In my app I would like to use UISwitch inside tableview cell. When I try to add target to my custom switch I got an error: "Segmentation fault: 11". The code is down below. How can I fix this?

let cellSwitch: UISwitch = {
let cellSwitch = UISwitch()
cellSwitch.translatesAutoresizingMaskIntoConstraints = false
cellSwitch.addTarget(self, action: #selector(handleSwitch(_:)), for: UIControlEvents.valueChanged)
return cellSwitch
}()

func handleSwitch(_ mySwitch: UISwitch) {
if mySwitch.isOn {
print("On")
} else {
print("Off")
}
}

Answer

Crashing with Segmentation fault: 11 is a bug of Swift compiler, and you should send a bug report to Apple or swift.org.

And in Swift 3, some sorts of bug in your code often triggers this compiler bug.

In your case, you cannot use self in the initial value of an instance property. One way to work this around is using lazy:

lazy private(set) var cellSwitch: UISwitch = {
    let cellSwitch = UISwitch()
    cellSwitch.translatesAutoresizingMaskIntoConstraints = false
    cellSwitch.addTarget(self, action: #selector(handleSwitch(_:)), for: UIControlEvents.valueChanged)
    return cellSwitch
}()

Another way is moving the assignment to cellSwitch to somewhere self is available. (Inside the viewDidLoad() maybe.)