如果在swift 3.1中任意绑定到任何一个的情况下如何使用

时间:2017-04-13 05:25:31

标签: ios iphone swift3 xcode8

我正在使用如果在swift的前一阶段循环,但在更新版本中我无法使用相同的循环。我试过使用后卫,但它也没有工作。

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或类似的东西。

2 个答案:

答案 0 :(得分:0)

我不确定,你的问题是什么,但我宁愿这样做:

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

稍微修改了我的代码。你不需要分开那个字符串

答案 1 :(得分:0)

试试这个:

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