cs193p – Assignment #1 Extra Task #2

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. Setting its value to nil should clear the display out. You’ll have to modify the code that uses displayValue accordingly.

If there is no text, or the text cannot be translated to a number, return nil, otherwise the number. If there is a value, set the labels, otherwise reset them:

private var displayValue: Double? {
  get {
    if let text = display.text, value = Double(text) {
      return value
    }
    return nil
  }
  set {
    if let value = newValue {
      display.text = String(value)
      history.text = brain.description + (brain.isPartialResult ? " …" : " =")
    } else {
      display.text = "0"
      history.text = " "
      userIsInTheMiddleOfTyping = false
    }
  }
}

Unwrap the changed property when necessary:

@IBAction private func performOperation(sender: UIButton) {
  ...
    brain.setOperand(displayValue!)
    ...
}

… and to reset the display, just set its value to nil:

@IBAction func clearEverything(sender: UIButton) {
  ...
  displayValue = nil
}

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

FacebooktwitterredditpinterestlinkedintumblrmailFacebooktwitterredditpinterestlinkedintumblrmail

One thought on “cs193p – Assignment #1 Extra Task #2”

  1. the getter for displayValue could be simpler: Double() returns an optional so if you just do:
    get { return Double(display.text!) } you should be done?

Leave a Reply

Your email address will not be published.