我对如何打开可选值感到困惑。我正在检查我的变量是否有任何值,我仍然得到一个错误。我试图在NSCollectionViewItem内执行此逻辑。那里不可能吗?无论我做什么,我都会收到这个错误:
致命错误:在解包可选值时意外发现nil
import Cocoa
class ImageCollectionView_Item: NSCollectionViewItem {
@IBOutlet weak var label: NSTextField!
var test: String?
override func viewDidLoad() {
super.viewDidLoad()
if test != nil {
print("success")
label.stringValue = "success"
} else {
print("fail")
label.stringValue = "fail"
}
}
}
答案 0 :(得分:1)
以快速方式展开可选值:
if let t = test {
//You can use t as the non optional value
//This if statement will run if test (t) is not nil
label.stringValue = "success"
}
else {
//This will run if test is nil
label.stringValue = "fail"
}