I have created user defaults with names below,
let prefs1 = UserDefaults.init(suiteName: \"UserAccount\")
let prefs2 = UserDefaults.init(suiteName: \"UserInfo\")
You can try
UserDefaults.standard.removeSuite(named: "UserAccount")
If you want to just remove the keys. You can go for following
func removeAllFor(defaults: UserDefaults) {
let dictionary = defaults.dictionaryRepresentation()
dictionary.keys.forEach { key in
defaults.removeObject(forKey: key)
}
}
Then you can call it on default that you want to clear data for
removeAllFor(defaults: prefs1)
removeSuite(named:) : Removes a sub-searchlist added via -addSuiteNamed method
removePersistentDomain(forName: ) : Removes all values from the search list entry specified by ‘domainName’.
I usually a different approach that also cleans up keys, based in idea "nil = no more exisiting":
// make property:
var userName: String? {
set(NewValue) {
self.setUserDefault(value: NewValue, for: USERNAME_KEY)
}
get{
let v = self.getFromUserDefaultsWith(key: USERNAME_KEY) as? String
return v
}
}
// accessory functions: (here the trick)
private final func getFromUserDefaultsWith(key: String) -> Any? {
let returnValue = UserDefaults.standard.object( forKey: key)
return returnValue
}
private final func setUserDefault(value: Any?, for key: String) {
let ud = UserDefaults.standard
if value == nil{
ud.removeObject(forKey: key)
}else{
ud.set(value, forKey: key)
}
ud.synchronize()
}
SO I can write:
final func wipeOut() {
// if nil, we remove... see above.
self.setUserDefault(value: nil, for: USERNAME_KEY)
}
func removePersistentDomain(forName domainName: String)
https://developer.apple.com/documentation/foundation/userdefaults/1417339-removepersistentdomain
Calling this method is equivalent to initializing a user defaults object with init(suiteName:) passing domainName, and calling the removeObject(forKey:) method on each of its keys.