How to auto clear NSUserDefault values in swift?

The swift counterpart for your objective-c code is this

 let appDomain = NSBundle.mainBundle().bundleIdentifier!

 NSUserDefaults.standardUserDefaults().removePersistentDomainForName(appDomain)

Swift 3.0 and higher

let appDomain = Bundle.main.bundleIdentifier!
UserDefaults.standard.removePersistentDomain(forName: appDomain)

check how many keys are already stored

print(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys.array.count)

add just another key

NSUserDefaults.standardUserDefaults().setBool(true, forKey: "justAnotherKey1")
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "justAnotherKey2")

check how many keys are already stored again (+2)

print(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys.array.count)

now create a loop to remove your object for the keys

for key in NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys {
    NSUserDefaults.standardUserDefaults().removeObjectForKey(key.description)
}

check how many keys you have again

print(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys.array.count)

update: Xcode 7.2.1 • Swift 2.1.1 (note NSUserDefaults doesn't work in playground anymore, so it needs to be tested in a real project)

print(Array(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys).count)

NSUserDefaults.standardUserDefaults().setBool(true, forKey: "justAnotherKey1")
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "justAnotherKey2")

print(Array(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys).count)

for key in Array(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys) {
    NSUserDefaults.standardUserDefaults().removeObjectForKey(key)
}

print(Array(NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys).count)

Swift 3.0 Solution

let appDomain = Bundle.main.bundleIdentifier!
UserDefaults.standard.removePersistentDomain(forName: appDomain)