Tuesday, August 1, 2017

Introduction to Delegate / Closure - Swift

Create a protocol IOSDeveloper , who can make applications for you //protocol are just blueprints . only declarations goes here..

protocol IOSDeveloper{

    func canMakeApplication(name:String)
}





Create a developer --> who actually create application
//conform it to that protocol 
//implement function -- canMakeApplication 

struct Developer : IOSDeveloper
{
    func canMakeApplication(name: String) {
        print("yes i can make IOS application \(name)")
    }
}



//create a dev object and ask if he can create application?

var vijay = Developer()
vijay.canMakeApplication(name: "vijay")



//create Client --> who want to create application
//As client don't know programming , so assign a delegate IOSDeveloper

struct Client {

    var delegate : IOSDeveloper?
}



//Create a client object 
//Assign developer object to client 
//And ask if he can create application for him

var myClient = Client()
myClient.delegate = vijay
myClient.delegate?.canMakeApplication(name: "client")





                       Closure

//by closure

struct Client {

    var makeApp : () -> Void = {}
    
    func DeveloperNeeded() {
        makeApp()
    }
}


struct Developer {

    func makeApp(){
    print("I am building apps for clients")
    }
}


var vijay = Developer()
var james = Client()

james.makeApp = vijay.makeApp

james.DeveloperNeeded()




No comments:

Post a Comment