Swift NSUserDefaults NSArray 使用 objectForKey [英] Swift NSUserDefaults NSArray using objectForKey
问题描述
我对 Swift 还很陌生,但我已经陷入了困境.
I'm pretty new to Swift, and I've managed to get pretty stuck.
我正在尝试从 NSUserDefaults
检索数据并将其存储在一个数组 (tasks
) 中:
I'm trying to retrieve data from NSUserDefaults
and store it in an array (tasks
):
@lazy var tasks: NSArray = {
let def = NSUserDefaults.standardUserDefaults()
let obj: AnyObject? = def.objectForKey("tasks")
return obj as NSArray
}()
我得到的只是一个警告:EXE_BAD_INSTRUCTION
在第 3 行.
All I'm getting is a warning: EXE_BAD_INSTRUCTION
on line 3.
还要注意,我实际上还没有设置任何数据,但我的目标是如果没有数据,我希望数组为空.我将使用这些数据来填充表格视图.
Also to note that I haven't actually set any data yet, but what I'm aiming for is that if there is no data, I want the array to be empty. I'll be using the data to populate a table view.
现在使用 var 而不是常量:
Now using a var instead of a constant:
@lazy var tasks: NSArray = {
let def = NSUserDefaults.standardUserDefaults()
var obj: AnyObject? = {
return def.objectForKey("tasks")
}()
return obj as NSArray
}()
错误现在已移至返回行.
The error has now moved to the return line.
推荐答案
我认为这里的问题是您试图将 nil
转换为非可选类型并返回它.Swift 不允许这样做.解决此问题的最佳方法如下:
I think the problem here is that you are attempting to cast nil
to a non-optional type and return it. Swift does not allow that. The best way to solve this would be the following:
@lazy tasks: NSArray = {
let defaults = NSUserDefaults.standardUserDefaults()
if let array = defaults.arrayForKey("tasks") as? NSArray {
return array
}
return NSArray()
}
将 Swift 的 if let
语法与 as?
运算符结合使用,可以让您在一行中进行赋值和安全转换.由于您的方法不返回可选项,因此如果转换失败,您必须返回一个有效值.
Using Swift's if let
syntax combined with the as?
operator lets you assign and safe cast in one line. Since your method does not return an optional, you must return a valid value if that cast fails.
这篇关于Swift NSUserDefaults NSArray 使用 objectForKey的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!