Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First time using button code

Tags:

button

swift

I have this variable

var taxableTotalText = String(28)

it is populated from a second view controller, it works well except when you use the app for the first time, if the string is blank it crashes the app. I have 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 "Has never been pushed" needs to be some real swift coding. At the moment i am just using

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

it stops my app from crashing but also forces my label to be "0.00" every time I reopen the app. A simple segue and back fixes the issue but its bugging me. Can someone please swap my english for swift, or suggest a better way to solve this issue. Thank you

like image 721
ElectricTiger Avatar asked Dec 02 '25 01:12

ElectricTiger


1 Answers

You can use the "??" nil coalescing operator to return a default value instead of nil.

TaxableTotal.text = NSUserDefaults().stringForKey("yourKey") ?? "0.00"
like image 126
Leo Dabus Avatar answered Dec 04 '25 20:12

Leo Dabus