class - Swift Delegation -


i'm having trouble wrapping head around delegation in swift. after reading guides, able set delegation between 2 viewcontrollers, i'm not understanding how works. in first view controller, have a label displays has been entered in second view controller contains text field , button (that returns first view controller). here code first view controller:

@iboutlet weak var labeltext: uilabel! func userdidenterinformation(info: string) {     labeltext.text = info; }   override func prepareforsegue(segue: uistoryboardsegue, sender: anyobject?) {     if(segue.identifier == "transition"){         let secondvc: secondviewcontroller = segue.destinationviewcontroller as! secondviewcontroller;         secondvc.delegate = self;      }     } 

here's code second view controller:

protocol dataentereddelegate{     func userdidenterinformation(info: string); }  @iboutlet weak var usertext: uitextfield! var delegate: dataentereddelegate? = nil;   @ibaction func buttonpressed(sender: anyobject) {     let information = usertext.text!;     delegate!.userdidenterinformation(information);     self.navigationcontroller?.poptorootviewcontrolleranimated(true);   } 

my understanding in text inside text field gets stored in information constant, userdidenterinformation method protocol called, method being defined inside first view controller. method changes label inside first view controller. thing is, i'm not sure happening in prepareforsegue function. specifically, i'm not sure what's purpose of secondvc.delegate = self.

i appreciate sort of clarity on delegation.

the diagram simple can understand what's going on.

diagram

firstviewcontroller must conform dataentereddelegate protocol have defined (see sumit's answer). when using secondvc.delegate = self, saying segue transition destination being secondviewcontroller, attribute delegate of secondviewcontroller instance set instance of firstviewcontroller, delegating things secondviewcontroller firstviewcontroller made possible dataentereddelegate protocol.


Comments