0

I am beginning to Alamofire recently. I want to use Alamofire to send a simple GET request:

import Alamofire

class Test{
    var url:String = "www.github.com"
    var i: Int = 1

    func change(){
        Alamofire.request(url, method:.get).responseString { response in
            self.i += 1
            print(self.i)
        }
        print(i)
    }
}

I want to change property i of class Test from 1 to 2 in Alamofire function call. And print results on console to see what would happen. I expect the output will be

2 2

but the real output is

1 2

!! I feel so confused about this result. Why it's not 2 2 or 2 1 but 1 2? what really happened during the function call? Why the property can't be changed?

Mojie11
  • 85
  • 1
  • 3
  • 11

1 Answers1

0

Because Alamofire request is an async, print(i) function runs before print(self.i) . You can achieve what you want by waiting the result of Alamofire with DispatchGroup(). However, I do not recommend it.

You can get more Info about using Dispatch on Alamofire:

iOS - swift 3 - DispatchGroup

Why It is a bad approach @Rob answered it very clearly on below post:

Synchronous Alamofire Request with DispatchGroup

Emre Önder
  • 2,408
  • 2
  • 23
  • 73