Good day! Help the newcomer to change the LoginViewController user variable. Here is the code below. Outside the UserService method UserService variable is a variable that changes in a block is equal to an empty array, while inside the block everything works and it is equal to an array of users.

I can not understand what's wrong

 class LoginViewController: UIViewController { var users = [User]() override func viewDidLoad() { UserService.getUsers() { users in self.users = users print(self.users) // Здесь выводятся юзеры print("1: \(self)") // Здесь LoginViewController } print(self.users) // Здесь выводится пустой массив print("2: \(self)") // Здесь LoginViewController } } 

PS Thanks in advance for your patience and help!

  • Trying to guess, UserService.getUsers () is some kind of request? (session.dataTaskWithURL for example), then the problem is that the work happens on different threads. - Vitali Eller
  • The answer has already been given on some other resource. The problem is that UserService.getUsers () is running asynchronously. I understand that print2 is executed before print1, which the questioner did not indicate. - Max Mikheyenko
  • Possible duplicate question: The array is unplanned becomes empty - VAndrJ

0