【问题标题】:How to use if let in case of optional binding to any in swift 3.1如果在 swift 3.1 中可选绑定到 any 时如何使用 if let
【发布时间】:2017-04-13 05:25:30
【问题描述】:

我在 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 或类似的。

【问题讨论】:

  • 图片的类型是什么?
  • 问题是什么?
  • 图片类型为一半 URL 其余部分由我提供。
  • @VladHatko 问题是如果让它显示错误,我将无法使用:条件绑定的初始化程序必须具有可选类型而不是任何
  • 我的回答能解决问题吗?

标签: ios iphone swift3 xcode8


【解决方案1】:

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

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

稍微编辑了我的代码。您也不需要分隔该字符串

【讨论】:

  • 在我们使用 Guard“非 void 函数应返回值”的两个地方都出现错误,据我了解,我们提供了 else {return} 那么为什么会这样?
  • 如果你的函数返回一个值,你必须在那里提供它。也许,你可以返回 nil
【解决方案2】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 2015-06-22
    • 2016-12-10
    • 1970-01-01
    相关资源
    最近更新 更多