Delete key values for NSUserDefaults in Swift

removeObjectForKey is the right way to go.
This will remove the value for the selected key. The following code sets a string value for a key in NSUserDefaults, prints it and then uses removeObjectForKey to remove and print the key value again. After removeObjectForKey the value is nil.

let prefs = NSUserDefaults.standardUserDefaults()
var keyValue = prefs.stringForKey("TESTKEY")
print("Key Value not set \(keyValue)")
let strHello = "HELLO WORLD"

prefs.setObject(strHello, forKey: "TESTKEY")
keyValue = prefs.stringForKey("TESTKEY")
print("Key Value \(keyValue)")

prefs.removeObjectForKey("TESTKEY")
keyValue = prefs.stringForKey("TESTKEY")
print("Key Value after remove \(keyValue)")

Returns:

Key Value not set nil

Key Value Optional("HELLO WORLD")

Key Value after remove nil

Update Swift 3:

let prefs = UserDefaults.standard
keyValue = prefs.string(forKey:"TESTKEY")
prefs.removeObject(forKey:"TESTKEY")

The code you have written will work fine, but NSUserDefaults synchronise at certain time interval.

As you want that should reflect in NSUserDefaults immediately ,so u need to write synchronise

let defaults = NSUserDefaults.standardUserDefaults()
defaults.removeObjectForKey("myKey") 
defaults.synchronize()

Try This

NSUserDefaults.standardUserDefaults().removePersistentDomainForName(NSBundle.mainBundle().bundleIdentifier!)

for Swift 3

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

But this will clear all values from NSUserDefaults.careful while using.


Removing UserDefaults for key in swift 3, based upon the top answer, just slightly different syntax:

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