1

I have the struct instance called users and Im parsing the JSON into this instance via closure but I came across that my edits don't save at all. So when I am out of the closure scope I have nil. Somebody know how to capture the value in closure?

var users: [User]! = [User]()

override func viewDidLoad() {
        super.viewDidLoad()

        Alamofire.request(url2).responseJSON { response in
            switch response.result {
            case .success(let value):
                guard let jsonArray = value as? [[String: Any]] else { return }
                self.users = jsonArray.compactMap(User.init)
                print(self.users!) // works
            case .failure(let error):
                print(error)
            }
        }

        print(users!) // error because I had nil
}
Stanislav Marynych
  • 188
  • 1
  • 1
  • 14

1 Answers1

1

Making a request takes time. To avoid the whole app from freezing up, the request is sent in the background and the program keeps executing, even if it didn't receive a response from the server yet.

A way around this is to call a separate function within the callback once the data has loaded. This could look as follows:

var users: [User]! = [User]()

override func viewDidLoad() {
        super.viewDidLoad()

        Alamofire.request(url2).responseJSON { response in
            switch response.result {
            case .success(let value):
                guard let jsonArray = value as? [[String: Any]] else { return }
                self.users = jsonArray.compactMap(User.init)
                print(self.users!) // works

                // call function here!
                self.usersLoaded()
            case .failure(let error):
                print(error)
            }
        }
}

func usersLoaded() {
        print(users!)
}
Felix Jassler
  • 1,029
  • 11
  • 22