Classes that require closures
Import UIKit//defining closure types (Specific function type function types)Typealias Inputclosuretype = (String),Void Protocol secondviewcontrollerdelegate:nsobjectprotocol{func fetchbackstring (str:string)}classSecondviewcontroller:uiviewcontroller {@IBOutlet weak var Inputtextfield:uitextfield!//receive the closing block from the last page.var backclosure:inputclosuretype?weak varDelegate: Secondviewcontrollerdelegate?Overridefunc viewdidload () {super.viewdidload ()//Do any additional setup after loading the view.} @IBAction func Tapbackbutton (Sender:uibutton) {ifSelf.backclosure! =Nil {ifLet tempstring =Self.inputTextField.text {self.backclosure!(tempstring)}} Self.navigationcontroller?. Popviewcontrolleranimated (true)} @IBAction func Delegatebackmethod (Sender:uibutton) {ifSelf.Delegate!=Nil {ifLet tempstring =Self.inputTextField.text {Delegate!. Fetchbackstring ("proxy return data: \ (tempstring)")}} Self.navigationcontroller?. Popviewcontrolleranimated (true) } Overridefunc didreceivememorywarning () {super.didreceivememorywarning ()//Dispose of any resources the can be recreated. }}
Calling a closure in another class
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. }}
Use of closures in swift (similar to block practice) packet value