在 Swift 4 中,
要将数组保存到用户默认值,您可以:
let defaults = UserDefaults.standard
let array = [25, 50]
defaults.set(array, forKey: "Scores")
并从用户默认值访问数组:
let defaults = UserDefaults.standard
let retrievedArray = defaults.array(forKey: "Scores") as? [Int] ?? []
如果您要在标签中显示数组的分数,您只需执行以下操作:
scoreLabel.text = String(describing: retrievedArray[0])
如果您在评分系统中使用整数,我建议您将分数存储为Int
用户默认值。
如果您更喜欢使用Strings
,请注意您可以stringArray(forKey:)
直接使用 User Defaults 的方法,而不是该array(forKey:)
方法,因此,在这种情况下,您不需要键入强制转换数组:
let someStringArray = defaults.stringArray(forKey: "ArrayOfStrings")
注意:为了回答您的问题,我认为您使用的是 Int 分数,但您可以随意使用任何您喜欢的分数。
If you want to store your array to the same key in User Defaults every time you get a new score, you could do it easily like this:
let defaults = UserDefaults.standard
// Your new score:
let newScore = 75
// Get your current scores list from User Defaults:
var currentArray = defaults.array(forKey: "Scores") as? [Int] ?? []
// Append your new score to the current array:
let updatedArray = currentArray.append(newScore)
// And save your updated array to User Defaults:
defaults.set(updatedArray, forKey: "Scores")
// In this example, your User Defaults now contains the updated array [25, 50, 75]
And that's it :).
Please note that there is no need to use an extension for that..
UPDATE: Also, if you want to add something inside your viewDidAppear
method, don't forget to add super.viewDidAppear(animated)
. The same goes for viewDidLoad
, etc.
The documentation states:
You can override this method to perform additional tasks associated
with presenting the view. If you override this method, you must call
super at some point in your implementation.
So you would have:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let retrievedArray = defaults.array(forKey: "Scores") as? [Int] {
print(retrievedArray)
// You can access your scores array safely here
}
}