Jenita _Alice4Real
Jenita _Alice4Real

Reputation: 131

How to unwrap guard statement in its body?

my error statement is :

variable declared in 'guard condition' is not usable in its body

and my code is:

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

the above is one a part of the program.

the error occurs in the line contains "data: imageData"

Thanks in advance!

Upvotes: 2

Views: 1796

Answers (1)

Sealos
Sealos

Reputation: 562

Consider this guard example:

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

And this if example:

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

In your case, you're mixing both concepts. You're using the guard as a if statement. You could change your guard to an if, or move the code outside of the else block.

The guard statement can be a bit confusing! Consider its use like the continue statement inside of a loop.

Upvotes: 3

Related Questions