Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Delegates in Swift 2 Delegation in iOS Implementing a Login Screen with Delegates

Why is the loginVC.delegate = self being used?

In the prepare for segue function, the line of code: loginVC.delegate = self

What does this do and why, if it is not implemented, does it stop the view controller from switching to Success Login page?

Davide Callegari
Davide Callegari
5,360 Points

He is basically telling to the login view controller that the delegate responsible for knowing that the user loggedin successfully is that view controller, the first view controller.

1 Answer

Anthony Boutinov
Anthony Boutinov
13,844 Points
  1. In LoginViewControllerDelegate protocol, we say that it requires that didLoginSuccessfully() method.
  2. Then for the class ViewController we specify that it conforms to that protocol.
  3. In ViewController, we implement that method.
  4. Now for the line "loginVC.delegate = self". When a person is on that Login Screen, when the login is successful, the delegate is called with didLoginSuccessfully() method to dismiss that screen. Since this method was implemented in our ViewController, in this line of code we say that this ViewController ("self" in Swift) is the one to whom the call should be made.

Answering the other question, yes, it does stop the view controller from switching to Success Login page, as you can see in the video when the teacher ran the simulator before adding that block of code. If you do not specify a delegate object for the stored property delegate: LoginViewControllerDelegate?, the call inside the loginButtonPressed() method (this line: delegate?.didLoginSuccessfully()) will unwrap nil and do nothing.