Search code examples
iosswiftnsuserdefaults

UserDefault should not remove only one key


I want to remove all object in userdefaults. while hitting the logout button. expect one bool key should not remove.May i know its possible

func resetUserDefaults() {

    print("userDefaults successfully removed from the app")

    let userDefaults = UserDefaults.standard
    let dict = userDefaults.dictionaryRepresentation()

    dict.keys.forEach { key in        
       userDefaults.removeObject(forKey: key)
     }
}

Solution

  • I'd prefer:

    for key in dict.keys where key != "YouBoolKey" {
        userDefaults.removeObject(forKey: key)
    }