-1

My code is not working. I don't know why. The problem is the property of switchChanged function. If property is empty then code is working.

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let rect = CGRectMake(130, 100, 0, 0)
    let uiSwitch = UISwitch(frame: rect)
    uiSwitch.setOn(true, animated: true)
    uiSwitch.addTarget(self, action: "switchChanged", forControlEvents: UIControlEvents.ValueChanged)

    self.view.addSubview(uiSwitch)
}

func switchChanged(uiSwitch: UISwitch) {
    var message = "Turn on the switch"
    if uiSwitch.on {
        message = "Turn off the switch"
    } else {
        message = "Turn on the switch"
    }
    let alert = UIAlertController(title: "Information", message: message, preferredStyle: UIAlertControllerStyle.Alert)
    let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)
    alert.addAction(action)
    self.presentViewController(alert, animated: true, completion: nil)
}

Error: "libc++abi.dylib: terminating with uncaught exception of type NSException"

1 Answers1

3

"switchChanged" is not the correct selector name, you should use "switchChanged:" to account for the parameter. switchChanged would be a method without parameters.

Also, in Swift you should use #selector(switchChanged(_:)) instead. That will validate the existence of selectors during compilation.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
  • uiSwitch.addTarget(self, action: #selector(ViewController.switchChanged(_:)), forControlEvents: UIControlEvents.ValueChanged) –  Oct 22 '16 at 18:09
  • @AlexanderStreltsov The `#selector` syntax has been introduced in Swift 2 so maybe you are still on Swift 1.x (Xcode 6)? – Sulthan Oct 22 '16 at 19:29
  • No, I have got Swift 2. I just don't have Swift 3 update. But i think it does not matter. –  Oct 23 '16 at 19:47