【问题标题】:How to unwrap guard statement in its body?如何在其正文中解开守卫声明?
【发布时间】:2016-08-31 09:29:36
【问题描述】:

我的错误陈述是:

在“保护条件”中声明的变量在其主体中不可用

我的代码是:

 extension ViewController {
  func uploadImage(image: UIImage, progress: (percent: Float) -> Void,
                   completion: (tags: [String], colors: [PhotoColor]) -> Void) {
    guard let imageData = UIImageJPEGRepresentation(image, 0.5) else {

      Alamofire.upload(
        .POST,
        "http://api.imagga.com/v1/content",
        headers: ["Authorization" : "Basic xxx"],
        multipartFormData: { multipartFormData in
          multipartFormData.appendBodyPart(data: imageData, name: "imagefile",
            fileName: "image.jpg", mimeType: "image/jpeg")
          }

以上是程序的一部分。

错误发生在包含“data: imageData”的行中

提前致谢!

【问题讨论】:

  • 我认为您将 guard let ... elseif let 混淆了。
  • 我第二个@EricAya
  • 那我应该做些什么修改呢?
  • ohh..你必须从 else 部分返回控制并在 else 块后执行操作。
  • else{..}块中的代码移到外面,替换为错误处理和return

标签: ios swift2 alamofire


【解决方案1】:

考虑这个 guard 示例:

guard let variable = optionalVariable else { return }
// Variable is safe to use here

还有这个 if 例子:

if let variable = optionalVariable {
    // Variable is safe to use here 
}

在您的情况下,您将这两个概念混为一谈。您将 guard 用作 if 语句。您可以将警戒更改为 if,或将代码移到 else 块之外。

guard 语句可能有点混乱!考虑将其用作循环内的 continue 语句。

【讨论】:

  • 嗯,这个想法是守卫声明不应该让你感到困惑...... OP应该想知道守卫后面的“其他”有什么好处......
猜你喜欢
  • 2017-12-13
  • 2019-09-20
  • 2021-01-29
  • 2017-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-11
  • 1970-01-01
相关资源
最近更新 更多