cs193p – Project #1 Assignment #1 Extra Task #4

By Marcin Wichary [CC BY 2.0 (http://creativecommons.org/licenses/by/2.0)], via Wikimedia Commons

Please note, this blog entry is from a previous course. You might want to check out the current one.

Change the computed instance variable displayValue to be an Optional Double rather than a Double. Its value should be nil if the contents of display.text cannot be interpreted as a Double (you’ll need to use the documentation to understand the NSNumberFormatter code). Setting its value to nil should clear the display out.

Make the display value an optional. When getting the display value, check first if there is a text, then if the text is a number and return the double value. Otherwise return nil. When setting the display value, check if it is nil. If not set the text label to the value otherwise to zero.

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

Update: I missed an “!” when setting the newValue … which resulted in an output like “Optional(123.0)” …

To adjust for the changed type only the the enter method needs a small tweak:

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

… and – not really necessary – you can change all occurrences where you set the display value to zero, to set it to nil.

The complete code for extra task #4 is available on GitHub.


3 thoughts on “cs193p – Project #1 Assignment #1 Extra Task #4”

  1. why not using optional chaining like this?

    get {
    return NSNumberFormatter().numberFromString(display.text!)?.doubleValue

  2. Thank you a lot for all your hard work. I have been stucked with some of the tasks for a few days and have no one to ask. You are hero!!

Leave a Reply

Your email address will not be published.