As a developer, we might use Userdefaults in our apps at some point in time for storing some basic configuration or settings in the app. But as the project gets complex, things can get pretty tough. Especially, when you want to clear all the UserDefaults values from the app. Well, we can use the removeObject method to remove the value for a particular key.

UserDefaults.standard.removeObject(forKey: "is_app_launched")

What if we have a vast number of keys, and we want to clear them all? Like 10 or 20 keys? If we try to clear all the keys using the removeObject method, we might miss clearing some values, and the code becomes complex. We don’t want to do that. So is there a better way? Yes, there is.

Apple provides us with a nice and clean API to deal with this. We can make use of the removePersistantDomainForName method to reset the UserDefaults.

if let bundleID = Bundle.main.bundleIdentifier {
    UserDefaults.standard.removePersistentDomain(forName: bundleID)
}

We can wrap the API in the UserDefaults extension to use it conveniently.

Clear UserDefaults

extension UserDefaults {
    static func resetDefaults() {
        if let bundleID = Bundle.main.bundleIdentifier {
            UserDefaults.standard.removePersistentDomain(forName: bundleID)
        }
    }
}

Using the API clears our UserDefaults completely, and leaves it in a fresh state. So yes, it might look insignificant, but it is a helpful API. Do you have other ways to clear the UserDefaults? Let me know in the comments below.

About the author