I'm using a Bool
UserDefault that I want to initially return as true
unless changed elsewhere in the app.
Unfortunately, UserDefault.bool(forKey:)
returns false
until stated otherwise. I would set it equal to true
in the viewDidLoad()
but that would result in it being reset every time that screen is loaded.
How do I change the initial default return value to true
instead of false
in swift?
Please use swift if possible.
It isn't totally clear what you are asking. Are you asking how to make it so that when your app is first installed and run, the value of your BOOL loads as true?
The answer is to use the registerDefaults()
method (as Martin R mentioned in his comment).
You pass it an NSDictionary containing the key/value pairs that you want to load as your "default defaults". The best place to do that is in the initialize class method for your app delegate. That way the default defaults key value pairs get set before any of your apps other code gets run.
So add this method to your app delegate:
class func initialize()
{
NSUserDefaults.standardUserDefaults().registerDefaults(
["myDefault": true,
"aStringDefault": "defaultStringValue"],
"arrayDefault": [1, 2, 3,])
//Do any other startup initialization that needs to happen
//before all your other app delegate code.
}
(Not tested. May need minor changes to work...)
You can register as many defaults as you like, and also write more complex structures into defaults. I updated the sample code to show a more complex example)