DirtyDev DirtyDev - 1 year ago 70
Swift Question

Swift throws error when trying to access segmented control index

Im currently learning swift and starting out with my first own calculator.
It all worked with a button to calculate the result, but I wanted to improve it a bit. The UI basically consists of two text fields for the numbers, one segmented control for the operators and one label to display the result. So thats what I want to happen:

Every time I change the segmented control value, a new result should be calculated and displayed.


[Calculator.MainInterfaceViewController operatorChanged:]: unrecognized selector sent to instance XXXX
... * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Calculator.MainInterfaceViewController operatorChanged:]: unrecognized selector sent to instance XXXX
First throw call stack:
libc++abi.dylib: terminating with uncaught exception of type NSException

My Class:

class MainInterfaceViewController: UIViewController, UITextFieldDelegate {

@IBOutlet var ersteZahl: UITextField!
@IBOutlet var zweiteZahl: UITextField!

@IBOutlet weak var ergebnisLabel: UILabel!
@IBOutlet weak var segment: UISegmentedControl!

override func viewDidLoad() {
ersteZahl.delegate = self;
zweiteZahl.delegate = self;

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

let newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string) as NSString
textField.text = newString as String
return false

@IBAction func operatorChanged() {

func refreshUIElements() {
let zahl1 = NSString(string: ersteZahl.text!).doubleValue
let zahl2 = NSString(string: zweiteZahl.text!).doubleValue

switch self.segment.selectedSegmentIndex {
case 0:
ergebnisLabel.text = "Ergebnis: \(zahl1 + zahl2)"
case 1:
ergebnisLabel.text = "Ergebnis: \(zahl1 - zahl2)"
case 2:
ergebnisLabel.text = "Ergebnis: \(zahl1 * zahl2)"
case 3:
if zahl2 == 0 {
ergebnisLabel.text = "Error: Cannot divide by 0."
ergebnisLabel.text = "Ergebnis: \(zahl1 / zahl2)"


Answer Source

I'm guessing you modified the method after it was autogenerated or tried to manually create it?

@IBAction's need a sender parameter. Something like this:

operatorChanged(sender: UISegmentedControl) {

Delete the method entirely and ctrl + drag from the storyboard again to the file. If the popup, choose action and give the method a name. Do not modify the method definition after this, or it will cause the same issue.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download