When working with swift, it's common case where we encounter in a situation where we want an object to perform the task on behalf of another object. The rescue to this is delegate. It is very same process of working of delegate like in objective c. But creating a custom delegate is little different then objective c in swift .
Lets look in example, here we are creating a custom delegate :
protocol userDelegate:class{
//list of methods
func userDidLogIn()
func userDidLogOut()
}
Class User: NSObject{
//make a singleton of the User class
static let sharedUser = User()
//define a property of the delegate
weak var delegate:userDelegate?
func logInUser(){
//here we can store the state of the user and perform some other task
//call delegate method
delegate?.userDidLogIn()
}
func logoutUser(){
//delete user detail from app
//call delegate method
delegate?.userDidLogOut()
}
}
Now to use this delegate, we can create a login view controller, where user will login , on successful login , we make a singleton User() object and call its method logInUser . In logIn view controller will conform to the userDelegate .
import UIKit
class LogInVc: UIViewController, userDelegate{
@IBAction func btnActn_userLogIn(sender:AnyObject){
//create user
let user = User.sharedUser
user. logInUser()
}
@IBAction func btnActn_logOut(sender:AnyObject){
let user = User.sharedUser
user. logoutUser()
}
Now it's time to implement delegate methods, here we can perform the post log in task.
func userDidLogIn(){
//perform post log in task here
}
func userDidLogOut{
//perform log out task here
}
}