1

I'm new in iOS programming and I was trying to get the value from User Defaults. I have some preferences and I'm trying to get them on the view controller.swift in the viewDidLoad() function.

Here is my code:

    override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
    let strName : NSString = defaults.objectForKey("name_preferences") as NSString
    let strEmail : NSString = defaults.objectForKey("mail_preferences") as NSString
    let strUser : NSString = defaults.objectForKey("user_preferences") as NSString

It crash in let strName, advising me: "fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)" I was supposed is because there wasn't any default value, so i typed it. But it still failing. Can anyone help me?

Ben Trengrove
  • 8,191
  • 3
  • 40
  • 58
fminondo
  • 21
  • 2

1 Answers1

1

This means that strName was not found in your user defaults. try this :

let var0 = defaults.objectForKey("key0") as? NSString 
let var1 = defaults.objectForKey("key1") as? NSString 
let var2 = defaults.objectForKey("key2") as? NSString //... and so on
if let strName = var0 {
   //use strName
}
if let strEmail = var1 {
   //use strEmail
}

If all of these must be present in the user defaults for your code to function correctly, you can nest the if let checks. If not, you should use conditionals for those values that can be nil.

You should do this for everything you take out of user defaults because you can't be sure that there will always be a correct type of object for your key.

EDIT :

Explanation : the as keyword is used for type casting. You can read about it here.

as? casts into an optional so if you cast a value to a type using as?, the code still works if the value was nil or cannot be cast. You can later check the optionals using an if let statement to see if they are nil or contain a value.

JohnVanDijk
  • 3,546
  • 1
  • 24
  • 27