Answer the question
In order to leave comments, you need to log in
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
}
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question