在 CKAsset 中检查 nil 时出错

error when checking for nil in CKAsset

我正在使用 CloudKit 并且在加载数据时我正在检查代码是否 CKAsset 为零,例如:

let img = result.value(forKey: "Picture") as! CKAsset
if  img != nil {

}

并出现以下错误:

"Comparing non-optional value type 'CKAsset' to nil always returns true

我知道它与可选项有关,但找不到解决方案。

img 不能是 nil,因为您将它强制转换为 CKAsset。当然,如果 result.value(forKey: "Picture") returns nil 或者它实际上不是 CKAsset.

,您的应用程序将在运行时崩溃

正确的编码方式如下:

if let img = result.value(forKey: "Picture") as? CKAsset {
    // do something with img
} else {
    // there is no Picture value or it's not actually a CKAsset
}