如何在 body 中展开 guard 语句?

How to unwrap guard statement in its body?

我的错误陈述是:

在 'guard condition' 中声明的变量在其 body

中不可用

我的代码是:

 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 示例:

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 语句。