[英]How to use if let in case of optional binding to any in swift 3.1
我在swift的前一個階段使用過if let loop,但是在更新版本中,我無法使用相同的循環。 我嘗試使用警衛隊守衛,但它也不起作用。
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]是可選值。 在某些情況下,可能無法從后端提供它,所以我想使用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()
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.