Xixiang Wu
Xixiang Wu

Reputation: 11

Swift unrecognized selector sent to instance

I am making a most basic calculator, learned from the Stanford online course. I only made a "multiply" button for it to multiply two values in Array "operandStack", but every time my program crashed and i don't know why.

    import UIKit

    class ViewController: UIViewController
        {
         @IBOutlet weak var display: UILabel!
         var userIsInTheMiddleOfTypingANumber:Bool = false

        @IBAction func appendDigit(sender: UIButton) {
               let digit = sender.currentTitle!
              if userIsInTheMiddleOfTypingANumber {
                 display.text = display.text! + digit
               } else {
                  display.text =  digit
                  userIsInTheMiddleOfTypingANumber = true
            }
         }

       @IBAction func operate(sender: UIButton) {
           let operation = sender.currentTitle!
           if userIsInTheMiddleOfTypingANumber {
             enter()
            }
           switch operation {
             case "×":
              if operandStack.count >= 2 {
                displayValue = operandStack.removeLast() * operandStack.removeLast()
                enter()
            }
             default: break
           }
        }
 var operandStack = Array<Double> ()

       @IBAction func enter() {
          userIsInTheMiddleOfTypingANumber = false
          operandStack.append(displayValue)
          println("operandStack = \(operandStack)")
        }


       var displayValue: Double {
         get {
            return   NSNumberFormatter().numberFromString(display.text!)!.doubleValue
        }
        set {
            display.text = "\(newValue)"
            userIsInTheMiddleOfTypingANumber = false
            }
        }
     }

Upvotes: 0

Views: 1833

Answers (1)

Jorge Luis Jim&#233;nez
Jorge Luis Jim&#233;nez

Reputation: 1308

I solve my problem when I noticed my plus sign, less sign and divided sign was connected with 2 Sent Event in Touch Up inside (View Controller -> appendDigit and operate). I disconnected my signs from appendDigit and it is working ok. Even I added a parameter in sender function

@IBAction func enter(sender: AnyObject?) {
    userIsInTheMiddleOfTypingANumber = false
    operandStack.append(displayValue)
    println("operandStack = \(operandStack)")
}

and I used the enter function like that: enter(sender). Another issue was this line of code:

return NSNumberFormatter().numberFromString(display.text!)!.doubleValue

I changed by this line:

return (display.text! as NSString).doubleValue

as I saw in this disscusion fatal error: unexpectedly found nil while unwrapping an Optional value - Stanford Calculator

I hope that helps programmer checking Stanford course.

Upvotes: 1

Related Questions