简体   繁体   English

在Swift 3.1中可选绑定的情况下如何使用

[英]How to use if let in case of optional binding to any in swift 3.1

I was using if let loop in previous stage of swift but in updated version I am unable to use the same loop. 我在swift的前一个阶段使用过if let loop,但是在更新版本中,我无法使用相同的循环。 I tried using guard let but it isn't working either. 我尝试使用警卫队守卫,但它也不起作用。

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()
    }
}

Here my image ie imageArray[0] is optional value. 在这里,我的图像即imageArray [0]是可选值。 It might not be supplied from backend in some cases so I want to use if let or similar. 在某些情况下,可能无法从后端提供它,所以我想使用let或类似的东西。

I'm not sure, what is your problem, but I would rather make it this way: 我不确定您的问题是什么,但是我宁愿这样:

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()
    }

Slightly edited my code. 稍微编辑了我的代码。 You don't need to separate that string, either 您也不需要分隔该字符串

try this : 尝试这个 :

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()
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM