First time using button code

I have this variable

var taxableTotalText = String(28)

      

it is populated from the second view controller, it works well except when you are using the app for the first time, if the string is empty it crashes the app. I tried

if taxableTotalText.isEmpty  {
    NSUserDefaults().setObject("0.00", forKey: String(28))
}

      

but it didn't work.

I would like to use some code like this

if TaxableAllowancesBtn "Has never been pushed" {     
    NSUserDefaults().setObject("0.00", forKey: String(28))
}
else {
       //do nothing
}
TaxableTotal.text = NSUserDefaults().stringForKey(taxableTotalText)

      

but "never been pushed" has to be some kind of real fast encoding. For now, I am just using

NSUserDefaults().setObject("0.00", forKey: String(28))

      

it stops my app from crashing and also makes my shortcut be "0.00" every time the app is reopened. Easy to switch and fix the problem, but bugging it. Maybe someone can change my english to fast or suggest a better way to solve this problem. Thanks you

+3


source to share


1 answer


You can use "??" nil coalescing operator return default instead of nil.



TaxableTotal.text = NSUserDefaults().stringForKey("yourKey") ?? "0.00"

      

+4


source







All Articles