Search code examples
iosswiftdoubleoption-typecs193p

UILabel variable needs to be an Optional Double but I don't want the the label to display optional(valueOfNumber)


I'm trying to complete the CS193P Course independently. I am on assignment 2 of the course and part of the assignment asks for me to do the following:

"Change the computed instance variable displayValue to be an Optional Double rather than a Double"

I was able to change displayValue to be an Optional Double, but now my UILabel which shows the displayValue now will display the optional value instead of the double value (which makes sense).

Example:

5 (then press enter) will display a value of Optional(5.0) in the UILabel.

Here is what I tried:

I determined that result and displayValue! will return a double.

I tried changing display.text = result to display!.text! = result but that did not fix the issue.

Here is a snippet of my code, I think you shouldn't need any more but please comment if you think I should show something else!

P.S. the name of the display is display

@IBAction func enter() {
    if let result = brain.pushOperand(displayValue!) {
        displayValue = result
    } else {
        displayValue = 0
    }
}

var displayValue: Double? {
    get {
        return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
    }
    set{
        display!.text! = "\(newValue)"     //display is the UILabel
    }

Solution

  • I believe the display is supposed to be blank when, for example, the stack cannot be evaluated to give a result.

    So you can just use

    var displayValue: Double? {
        get { return NSNumberFormatter().numberFromString(display.text!)?.doubleValue }
        set { if newValue != nil { display.text = "\(newValue!)" }
                else { display.text = " " }
        }
    }
    

    And then for "enter"

    @IBAction func enter() {
        if let dV = displayValue {
            brain.pushOperand(dV)
            displayValue = brain.evaluate()
        }
        userIsInTheMiddleOfTypingANumber = false
    }
    

    This solution worked for me. I am working through this course independently too. It is tricky and I have to listen to the lectures LOTS of times :-)

    Jacki