Stevik
Stevik

Reputation: 1152

Store dictionary with optional values [String: AnyObject?] in NSUserDefaults

I need to store a dictionary that which can contain a nil as a value

Example

var someOptionalVar: String? = nil

var dict: [String: AnyObject?] = [
    "someOptionalVar": self.someOptionalVar
]

defaults.setObject(dict, forKey: self.nsUserDefaultsKey)

But it gives me this error

Cannot convert value of type '[String: AnyObject?]' to expected argument type 'AnyObject?'

I know I could leave the nil variables and then when I'm parsing the dictionary from NSUserDefaults I would set variables (corresponding to the missing properties) to nil, but this is not what I would like to do.

So how can I store nil values in NSUserDefaults ?

Upvotes: 1

Views: 1216

Answers (1)

Lasse
Lasse

Reputation: 650

Use NSNull() instead of nil, and declare the dictionary to contain only non-optionals:

var someOptionalVar: String? = nil

var dict: [String: AnyObject] = [
    "someOptionalVar": self.someOptionalVar ?? NSNull()
]

defaults.setObject(dict, forKey: self.nsUserDefaultsKey)

Upvotes: 6

Related Questions