This seems a bug. I am trying to remove an existing value in the defaults.
UserDefaults.standard.set(nil, forKey: "test-me")
let val = UserDefaults.standard.object(forKey: "test-me")
print ("val=\(val)")
I got the following output -
val=Optional(<62706c69 73743030 d4010203 04050608 09582476 65727369 6f6e5824 6f626a65 63747359 24617263 68697665 72542474 6f701200 0186a0a1 0755246e 756c6c5f 100f4e53 4b657965 64417263 68697665 72d10a0b 54726f6f 74800008 111a232d 3237393f 51545900 00000000 00010100 00000000 00000c00 00000000 00000000 00000000 00005b>)
I am running in XCode 8 / iOS 10 / iPhone 7 simulator.
Writing or Setting Values To User Defaults You simply invoke the set(_:forKey:) method on the UserDefaults instance. In this example, we set the value of myKey to true by invoking the set(_:forKey:) method on the shared defaults object.
An interface to the user's defaults database, where you store key-value pairs persistently across launches of your app.
UserDefaults can simply save custom object which conforms to Codable protocol. JSONEncoder and JSONDecoder play important roles for handling the data transformation. Nested object must also conform to Codable protocol in order to encode and decode successfully.
We access the shared defaults object through the standard class property of the UserDefaults class. We then create a dictionary of type [String:String] and store the dictionary in the user's defaults database by invoking the set(_:forKey:) method of the UserDefaults database.
The comment from Rob in the other post looks correct. Setting the value to "nil" will save it as NSData. To remove the key, try this instead:
UserDefaults.standard.removeObject(forKey: "test-date")
You will then probably get back "nil" when doing object(forKey: "test-date")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With