Ios 在swift 3.1中任意绑定的情况下,如何使用if let

Ios 在swift 3.1中任意绑定的情况下,如何使用if let,ios,iphone,swift3,xcode8,Ios,Iphone,Swift3,Xcode8,我在swift的前一阶段使用了if-let循环,但在更新版本中,我无法使用相同的循环。我试过使用guard let,但也不起作用 let imageArray = dataObject?["image"] as! NSArray if let image = imageArray[0]{ let imageURL = "compute.amazonaws.com/" + "\(image)" print(imageURL) if

我在swift的前一阶段使用了if-let循环,但在更新版本中,我无法使用相同的循环。我试过使用guard let,但也不起作用

let imageArray = dataObject?["image"] as! NSArray
    if let image = imageArray[0]{
         let imageURL = "compute.amazonaws.com/" + "\(image)"
         print(imageURL)  
         if let url: URL = URL(string:"\(imageURL)")!{
        let task = URLSession.shared.dataTask(with: url, completionHandler: { (responseData, responseUrl, error) -> Void in
            if let data = responseData{
                DispatchQueue.main.async(execute: { () -> Void in
                    cell?.imageViewProduct.image = UIImage(data: data)
                })
            }
        })
        task.resume()
    }
}

这里我的图像,即imageArray[0]是可选值。在某些情况下,它可能不是从后端提供的,所以我想使用if-let或类似的

我不确定,你有什么问题,但我宁愿这样说:

guard let imageArray = dataObject?["image"] as? [String] else {return} //as I understand, names of images here
    guard let image = imageArray.firstObject else {return}

    let imageURL = "compute.amazonaws.com/\(image)"
    print(imageURL)

    if let url = URL(string:"\(imageURL)") {
        let task = URLSession.shared.dataTask(with: url, completionHandler: { (responseData, responseUrl, error) -> Void in
            if let data = responseData{
                DispatchQueue.main.async(execute: { () -> Void in
                    cell?.imageViewProduct.image = UIImage(data: data)
                })
            }
        })
        task.resume()
    }
稍微编辑了我的代码。您不需要分隔该字符串,也可以尝试以下操作:

let imageArray = dataObject?["image"] as! NSArray
if let image = "\(imageArray[0])" as? String{
     let imageURL = "compute.amazonaws.com/" + "\(image)"
     print(imageURL)  
     if let url: URL = URL(string:"\(imageURL)")!{
    let task = URLSession.shared.dataTask(with: url, completionHandler: { (responseData, responseUrl, error) -> Void in
        if let data = responseData{
            DispatchQueue.main.async(execute: { () -> Void in
                cell?.imageViewProduct.image = UIImage(data: data)
            })
        }
    })
    task.resume()
}
}

图像的类型是什么?问题是什么?图像的类型是URL的一半,其余部分应该由我提供。@VladHatko的问题是,如果让它显示错误,我将无法使用:条件绑定的初始值设定项必须具有可选类型。我的答案解决了问题吗?在使用Guard的两个位置都签了错误“非void函数应该返回一个值”根据我的理解,我们有supplie else{return}那么为什么呢?如果你的函数返回一个值,你必须在那里提供它。也许,你可以返回nil