Firstviewcontroller's Code
Import UIKitclassFirstviewcontroller:uiviewcontroller, secondviewcontrollerdelegate {@IBOutlet weak var showtextlabel:uilabel!@IBOutlet weak var showdelegatetextlabel:uilabel!Overridefunc viewdidload () {super.viewdidload ()//Do any additional setup after loading the view. } //Click the button to jump to Secondviewcontroller@IBAction func Tapgosecondviewcontroller (Sender:uibutton) {//load Secondviewcontroller from storyboardLet SECONDVC = Uistoryboard (name:"Main", Bundle:NSBundle.mainBundle ()). Instantiateviewcontrollerwithidentifier ("Secondviewcontroller") as!Secondviewcontroller//implement callback to get back value of callback (closure) Secondvc.backclosure ={(backstr:string)-VoidinchSelf.showTextLabel.text=backstr} SECONDVC.Delegate= Self//Jump to SecondviewcontrollerSelf.navigationcontroller?. Pushviewcontroller (SECONDVC, animated:true) } //MARK:-secondviewcontrollerdelegate(agent) func fetchbackstring (str:string) {Self.showDelegateTextLabel.text=STR}Overridefunc didreceivememorywarning () {super.didreceivememorywarning ()//Dispose of any resources the can be recreated. }}
SecondviewcontrollerThe Code
Import uikit//defines the closure type (Specific function type function type) Typealias Inputclosuretype = (String), Voidprotocol secondviewcontrollerdelegate:nsobjectprotocol{func fetchbackstring (str:string)}class SecondViewController: Uiviewcontroller {@IBOutlet weak var inputtextfield:uitextfield! Receive the last page sent over the closure block Var backclosure:inputclosuretype? Weak var delegate:secondviewcontrollerdelegate? Override Func Viewdidload () {super.viewdidload ()//Do any additional setup after loading the view. } @IBAction func Tapbackbutton (Sender:uibutton) {if self.backclosure! = nil {if let tempstring = S Elf.inputTextField.text {self.backclosure! ( tempstring)}} Self.navigationcontroller?. Popviewcontrolleranimated (True)} @IBAction func Delegatebackmethod (Sender:uibutton) {if self.delegate ! = Nil {if let tempstring = self.inputTextField.text {delegate!. Fetchbackstring ("Proxy return data: \ (tempstring)}} Self.navigationcontroller?. Popviewcontrolleranimated (True)} override Func didreceivememorywarning () {super.didreceivememorywarning ()//Dispose of any of the resources that can be recreated. }}
Effect View:
Swift uses proxies and closures (closure) to reverse the value