问题描述
我已经阅读了我能找到的所有关于此的 stackoverflow 文章,但由于某种原因,按照他们所说的去做是行不通的。
我想将一个字符串数组(一次 1 个字符串)保存为用户默认值,然后出于我自己的考虑打印出整个数组。
我的代码的输出总是“allItems 数组为空”。
这是我的代码,谢谢:
// new string to save
let newAddition = "new string"
// retrieve all items in array from userdefaults
let defaults = UserDefaults.standard
var allItems = defaults.array(forKey: "Key") as? [String]
// add new item
allItems?.append(newAddition)
// re-save the plan array
defaults.set(allItems,forKey: "Key")
printItems()
func printItems() {
// retrieve all items in array from userdefaults
let defaults = UserDefaults.standard
let allItems = defaults.array(forKey: "Key") as? [String] ?? []
if allItems.count != 0 {
for plan in 0 ..< (allItems.count-1) {
print("item name: \(plan)")
}
}
else {
print("allItems array is empty")
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)