swift 获取条件绑定的错误初始值设定项必须具有可选类型,为什么?

swift getting error initializer of conditional binding must have optional type, why?

我正在使用 swift 和 cloudkit 尝试从云服务器获取图像,如下所示,我收到错误:"initializer of conditional binding must have optional type not CKAsset" 在行:if let ckAsset = image { 请帮忙,因为我是 swift 的新手,这是我的第一个应用程序

 let ckRecord = Saveddata[indexPath.row]
    weak var weakCell = cell
    backgroundQueue.addOperation {
        let image = ckRecord.object(forKey: "Photos") as! CKAsset

        if let ckAsset = image {
            if let URL = ckAsset.fileURL {
            let imagedata = NSData(contentsOf: URL)
            OperationQueue.main.addOperation() {
                cell.imageView?.image = UIImage(data: imagedata! as Data)
                }

        }

        }

我想你要找的是这个:

let ckRecord = Saveddata[indexPath.row]
weak var weakCell = cell
backgroundQueue.addOperation {
    let image = ckRecord.object(forKey: "Photos")

    // Conditionally cast image resource
    if let ckAsset = image as? CKAsset {
        // This isn't optional, no protection needed
        let url = ckAsset.fileURL

        // Data(contentsOf:...) will throw on failure
        do {
            // Fetch the image data (try because it can fail and will throw if it does)
            let imagedata = try Data(contentsOf: url)
            OperationQueue.main.addOperation() {
                weakCell?.imageView?.image = UIImage(data: imagedata)
            }
        }
        catch {
            // handle data fetch error
        }
    }
}

它有条件地将资源转换为 CKAsset 并且仅当它确实是一个时才继续。