-3

Im creating simple app where i can manipulate my display which holds numbers(double). App works perfectly on simulator but not on a real device.

I found the reason for that error. Its my getter. Its returning nil(pretty sure about that) Anyone got idea how to fix my getter?

var displayValue: Double {
    get {
        return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
    }
    set {
        display.text = String(format: "%g", newValue)

    }
}
Bartosz
  • 378
  • 3
  • 11
  • 1
    Avoid using `!` (force unwrapping), use safe unwrapping instead with `if let` and other known techniques: http://stackoverflow.com/questions/24018327/what-does-an-exclamation-mark-mean-in-the-swift-language – Eric Aya Jan 13 '16 at 17:19
  • 1
    Any time you have an exclamation mark in your Swift code, you can crash. Rewrite without the exclamation marks. – matt Jan 13 '16 at 17:19
  • you could let your `displayValue` be an optional (`... : Double?`) and use `return NSNumberFormatter().numberFromString(display.text ?? "")?.doubleValue` – dfrib Jan 13 '16 at 17:24
  • Creating a new NSNumberFormatter every time you want to get that value is very unnecessarily inefficient. Create it once at the beginning of the object's life and reuse it. – Will M. Jan 13 '16 at 18:27

2 Answers2

0

You must be trying to get value of displayValue before assigning it any value, and your are force unwrapping it so, obviously it will crash.

In your current code just try setting value to your display label (like display.text = "5") before accessing it, then it would work.

And its better to use if let check in case of force unwrapping, if you know your variable value can be nil.

Ajay Kumar
  • 1,807
  • 18
  • 27