ios - value 不为零,但在解包可选值时意外发现 nil

标签 ios objective-c swift watchkit

我正在尝试将一些数据从数组发送到其他接口(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/

相关文章:

ios - 从存储在结构体创建的数组中的选定表格单元格中播放音频

ios - 如何在应用程序处于后台时将推送通知有效负载插入数据库

macos - 如何清除 NSTableView 的内容并在单击 Swift 中的按钮时再次重新加载数据

ios - 如何更好地理解可选项

ios - 如何进行 Facebook 风格转换

ios - 我如何调试此错误 : CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER?

objective-c - xcode 8.3 框架找不到体系结构 armv7 的 FileProvider

objective-c - "Missing context for method declaration"用于覆盖描述方法

swift - 按国家 ISO 获取 NumberFormatter 货币

ios - 布局 UIView 而不将其添加到 subview