L
L
loogle182017-02-06 19:00:48
iOS
loogle18, 2017-02-06 19:00:48

How to change global controller variable?

Good afternoon! Help a newbie change the users variable of the LoginViewController. Here is the code below. Outside the UserService method, the user variable that will change in the block is equal to an empty array, while inside the block everything works and it is equal to the array of users.
I can't figure out what's wrong. Perhaps you can suggest another solution to my problem.

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!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Zhilin, 2017-02-06
@loogle18

Perhaps UserService.getUsers is an asynchronous operation. In this case, the code in the closure will run later than the code after the getUsers call.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question