OGeek|极客世界-中国程序员成长平台

标题: ios - 如何在其正文中解开守卫声明? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 12:00
标题: ios - 如何在其正文中解开守卫声明?

我的错误陈述是:

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

我的代码是:

 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”的行中

提前致谢!



Best Answer-推荐答案


考虑这个 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 block 之外。

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

关于ios - 如何在其正文中解开守卫声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39245779/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4