fs_tigre fs_tigre - 1 year ago 110
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

key exists in

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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download