Store [String] in NSUserDefaults(Swift)

前端之家收集整理的这篇文章主要介绍了Store [String] in NSUserDefaults(Swift)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想把一个Swift样式字符串数组保存到NSUserDefaults,但是在代码中的“if”语句表示returnValue总是nil。

后来在代码中我想使用“food = [”spaghetti“]来添加新条目。

var food : [String] {
    get {
        var returnValue : [String]? = NSUserDefaults.standardUserDefaults().objectForKey("food") as? [String]
        if returnValue == nil      //Check for first run of app
        {
            returnValue = ["muesli","banana"]; //Default value
        }
        return returnValue!
    }
    set (newValue) {
        NSUserDefaults.standardUserDefaults().setObject(newValue,forKey: "food")
        NSUserDefaults.standardUserDefaults().synchronize()
    }
}
以下代码可以帮助您解决问题:
import UIKit

class ViewController: UIViewController {

    var food: [String] {
        get {
            if let returnValue = NSUserDefaults.standardUserDefaults().objectForKey("food") as? [String] {
                return returnValue
            } else {
                return ["muesli","banana"] //Default value
            }
        }
        set {
            NSUserDefaults.standardUserDefaults().setObject(newValue,forKey: "food")
            NSUserDefaults.standardUserDefaults().synchronize()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        print(food) // prints: ["muesli","banana"] (at first launch)

        food = ["cake"]
        print(food) // prints: ["cake"]

        food += ["spaghetti"]
        print(food) // prints: ["cake","spaghetti"]

        food = []
        print(food) // prints: []

        NSUserDefaults.standardUserDefaults().setObject(nil,forKey: "food")
        print(food) // prints: ["muesli","banana"]
    }

}

然而,使用上面的代码,如果你设置food = [],你会有一个问题,因为食物不会返回[“muesli”,“banana”]。为了避免这种情况,你可能更喜欢下面的代码

import UIKit

class ViewController: UIViewController {

    var food: [String] {
        get {
            if let returnValue = NSUserDefaults.standardUserDefaults().objectForKey("food") as? [String] {
                return returnValue == [] ? ["muesli","banana"] : returnValue
            } else {
                return ["muesli","spaghetti"]

        food = []
        print(food) // prints: ["muesli","banana"]

        NSUserDefaults.standardUserDefaults().setObject(nil,"banana"]
    }

}
原文链接:https://www.f2er.com/swift/321017.html

猜你在找的Swift相关文章