fs_tigre fs_tigre - 1 month ago 7
Swift Question

What is the proper way to check if a Boolean key exists in NSUserdefaults/UserDefaults

Which of the two examples below is best for checking if a

boolean
key exists in
NSUserdefaults
?

1- Is this acceptable?

if NSUserDefaults.standardUserDefaults().boolForKey("myKey"){
print("Key Does Exist")
}


2- Is this the preferred way?

if (NSUserDefaults.standardUserDefaults().objectForKey("myKey") != nil) {
print("Key Does Exist")
}

Answer

If you want to verify if something is stored for a key, the second option is fine (Swift 3).

if (NSUserDefaults.standardUserDefaults().object(forKey: "myKey") != nil) {
     print("Key Does Exist")
}

object(forKey:) documentation mentions that nil is returned if the key is not found.


But if you want to verify if something is stored for a key, and it's actually a Boolean: neither versions are fine.

  • First verifies if the Boolean value exists and actually is true.
  • The second verifies if an object exists, but you can't be sure it's a Boolean.

Check the following possibility (Swift 3):

if let boolValue = NSUserDefaults.standardUserDefaults().object(forKey: "myKey"), 
  boolValue is Bool {
  // Boolean exists
}
Comments