Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UserDefaults.standard set nil Error in XCode 8 and Swift 3

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.

like image 516
BSharer App - Share Books Avatar asked Sep 15 '16 19:09

BSharer App - Share Books


People also ask

How do I get UserDefaults in Swift?

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.

What is the UserDefaults in Swift?

An interface to the user's defaults database, where you store key-value pairs persistently across launches of your app.

Can we store custom object in UserDefaults Swift?

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.

How do I save a dictionary in Swift?

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.


1 Answers

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")

like image 127
Myke Olson Avatar answered Sep 19 '22 01:09

Myke Olson