0

I'm following the Stanford Videos for iOS development and I am using Xcode 7 with Swift 2. I wrote the code from the video line by line, however I keep getting an error.

import UIKit

class ViewController: UIViewController
{

@IBOutlet weak var display: UILabel!

var userIsTyping = false

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

var operandStack = Array<Double>()

@IBAction func enter() {
    userIsTyping = false
    operandStack.append(displayValue)
}

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

    }
}


}

At the line where I return

NumberFormatter().numberFromString(display.text!)!.doubleValue

I get an error of

Thread 1: EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP,subcode=0x0)

1
  • 1
    Your label display is nil or contains not-number-string. Commented Dec 25, 2015 at 2:23

3 Answers 3

1

A conversion can fail. The result can be nil. The "!" means "compiler, I am 100 percent sure that the result can never be nil, so if it is ever nil then please crash". Guess what, sometimes it is nil.

Use "if let".

PS. I think it is very, very unhealthy to take user interface elements (like the title of a button) and to assume they have certain values.

Sign up to request clarification or add additional context in comments.

1 Comment

Indeed. There is this thing called "user input sanitation/validation".
0

You are much better off substituting that return statement with a much simpler:

return Double(display.text!)!

Comments

0

let Number = (NSNumberFormatter().numberFromString(xtxt.text!)as! Double)

 return Number

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.