The problem is that you print the contents of UserDefaults immediately after they are cleared, but you do not synchronize them manually.
let domain = Bundle.main.bundleIdentifier! UserDefaults.standard.removePersistentDomain(forName: domain) UserDefaults.standard.synchronize() print(Array(UserDefaults.standard.dictionaryRepresentation().keys).count)
That should do the trick.
Now you usually donโt need to call synchronize manually, since the system automatically synchronizes userDefaults, but if you need to push the changes immediately, you need to force update using the synchronize call.
The documentation states this
Since this method is automatically called at periodic intervals, use this method only if you cannot wait for automatic synchronization (for example, if your application is about to exit) or if you want to update the user's default disk settings, even if you have not made any changes.
source share