我正在尝试将一些数据从数组发送到其他接口(interface) Controller 。问题是我得到了
unexpectedly found nil while unwrapping an Optional value exception
即使数组不为零。事实上,我什至可以使用
打印结果打印(...)。
问题是我无法在不出现异常的情况下将此结果设置为标签。
这是我的代码,用于使用上下文数据笑新的界面 Controller
@IBAction func lauchInterfaceClick() {
presentControllerWithName("SecondInterface", context: ["hi","how are you"])
}
然后在 SecondInterface 中检索结果,如下所示
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
if context != nil{
let somevalue = context as! [String]
// here is where I getting the exception, in addition to Thread 1: EXC_BAD_INSTRUCTION (code=EXC_i386_INVOP, subcode=0x0)
self.showWat.setText(String(somevalue[0]))
// I have also tried this
// self.showWat.setText(somevalue[0])
}
请注意,另一方面 print(String(somevalue[0]))
输出 hi
最佳答案
我将使用 awakeWithContext(context: AnyObject?)
的实现,如下所示:
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
if context != nil{
let somevalue = context as? [String] {
if somevalue.count > 0 {
let text = somevalue[0]
showWat.setText(text)
}
} else {
// Unwrapped optional is nil
print("someValue is nil!")
}
}
}
查看 Swift Programming Language Reference 中的“可选链接作为强制展开的替代方案”部分.
或者查看这个answer这里是关于堆栈溢出的内容。
关于ios - value 不为零,但在解包可选值时意外发现 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34875110/