Chen Li Yong Chen Li Yong - 2 months ago 9
Swift Question

How to write inside a dictionary entry in NSUserDefaults without using temporary variables?

I have this code:

var address = Dictionary<String, AnyObject?>();
address["address1"] = "Here";
address["address2"] = "There";
...
let defaults = NSUserDefaults.standardUserDefaults();
var data = defaults.valueForKey("active_user")! as! Dictionary<String, AnyObject?>
data["address"] = address;
defaults.setValue(data, forKey: "active_user");
defaults.synchronize();


I want to change it into like this:

var address = Dictionary<String, AnyObject?>();
address["address1"] = "Here";
address["address2"] = "There";
...
let defaults = NSUserDefaults.standardUserDefaults();
defaults["active_user"]!["address"]! = address;
defaults.synchronize();


Is this possible? How can I do that?

Answer

I donĀ“t think that is possible unfortunately. You need to use setValue to set a value. For example to set an int you use setInteger and string setObject etc.