如何在不使用临时变量的情况下在NSUserDefaults中写入字典条目?

时间:2016-08-30 08:40:02

标签: swift dictionary nsuserdefaults

我有这段代码:

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();

我想把它改成这样:

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

这可能吗?我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

通过将NSUserDefaults扩展为下标,可以实现这一点。见下文:

sort

然后可以这样使用:

extension NSUserDefaults {

    subscript(key: String) -> Any {

        get {

            return value(forKey: key)
        }

        set {

            setValue(newValue, forKey: key)
        }
    }
}

一个限制是,您将无法像在示例中那样修改嵌套集合。您将始终必须手动分配回用户默认对象以保存内容。

let defaults = NSUserDefaults.standardUserDefaults()

defaults["myKey"] = "someValue"

let myValue = defaults["myKey"]

编辑:

我想出了一种重载下标的方法,这样你就可以 修改嵌套集合,语法略有不同但非常干净。只适用于嵌套的一个级别,但我认为可以进一步采用。将其添加到您的// this won't work defaults["active_user"]!["address"]! = address; // do this instead let user = defaults["active_user"]! user["address"] = address defaults["active_user"] = user 扩展程序中:

NSUserDefaults

然后你可以这样做:

subscript(firstKey: String, secondKey: String) -> Any? {

    get {

        if let dict = value(forKey: firstKey) as? [String: Any] {

            return dict[secondKey]
        }

        return nil
    }

    set {

        if let dict = value(forKey: firstKey) as? [String: Any] {

            dict[secondKey] = newValue

            setValue(dict, forKey: firstKey)
        }
    }
}