微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swift - 条件绑定的初始化程序必须具有 Optional 类型,而不是“PHFetchResult<PHAsset>”

如何解决Swift - 条件绑定的初始化程序必须具有 Optional 类型,而不是“PHFetchResult<PHAsset>”

将 Xcode 更新到 12.3 后,我收到错误“条件绑定的初始化程序必须具有可选类型,而不是‘PHFetchResult’”,它在以前的版本中按预期工作。

func fetchRecentPhotos() {
    
    if !self.recentimagesArray.isEmpty{return}
    dispatchQueue.global(qos: .default).async {
        let fetchOptions = PHFetchOptions()
        fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate",ascending: false)]
        
        if let fetchResult : PHFetchResult = PHAsset.fetchAssets(with: .image,options: fetchOptions){
            if fetchResult.count > 0 {
                self.recentimagesArray.removeAll()
                for i in 0..<fetchResult.count {
                    let asset =  fetchResult.object(at: i)
                    self.recentimagesArray.append(Recentimage(asset: asset))
                }
                dispatchQueue.main.async {
                    if !self.isVideoStarted{
                        self.recentimagesCollectionView.reloadData()
                        self.recentMediaCollectionHeight.constant = 100
                        print("\(Date())fetchRecentPhotos ===== done")
                        if !self.isMultipleSelection{
                            self.setupGesturesForCameraSelection()
                        }
                        UIView.animate(withDuration: 0.2,animations: {
                            self.view.layoutIfNeeded()
                        })
                    }
                }
            }else{
                print("you got no photos")
            }
        }
    }
    }

有人解决了这个问题吗?

enter image description here

解决方法

请快速浏览一下 documentationfetchAssets 返回非可选值,因此您不得使用 if let

替换

if let fetchResult : PHFetchResult = PHAsset.fetchAssets(with: .image,options: fetchOptions){ ... }

let fetchResult = PHAsset.fetchAssets(with: .image,options: fetchOptions)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。