Saturday, May 30, 2015

Swift syntax for closure and generic alertbox function

Closure in swift is corresponding to block in Objective C, but its syntax is quite different from block in objective C, or other languages. One thing to notice is closure syntax in swift is quite similar to function definition, but without parameter name.

For example, the beginBackgroundTaskWithName defined in UIApplication class has closure parameter handler as shown below, which takes no parameter () and return Void. In addition, the closure can be nil indicated by the optional type flag ?.

func beginBackgroundTaskWithName(_ taskName: String?,
               expirationHandler handler: (() -> Void)?) -> UIBackgroundTaskIdentifier

A sample code to call the method may looks like:
    var bgTask :UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
     bgTask = application.beginBackgroundTaskWithName("logout", expirationHandler: { () in
            ...
            application.endBackgroundTask(bgTask)
            bgTask = UIBackgroundTaskInvalid;
     });

Now, let take UIAlertAction as a sample to create a generic alertbox. The constructor of UIAlertAction takes a closure parameter handler, which takes a UIAlertAction parameter and return Void. the handler is not optional indicated by !
UIAlertAction(title title: Stringstyle style: UIAlertActionStylehandler handler: ((UIAlertAction!) -> Void )!)

Let see how to create a generic alertbox that takes a title, message, buttonTitle and handler parameters, and once ok is clicked, it will call the handler parameter passed to it

func alert(title: String, message: String, buttonTitle: String, handler:((UIAlertAction!) -> Void )!){             var alertDlg : UIAlertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
    
        var okAction : UIAlertAction = UIAlertAction(title: buttonTitle, style: UIAlertActionStyle.Default, handler:handler);
                    
         alertDlg.addAction(okAction)
         self.presentViewController(alertDlg, animated: false, completion: nil)
 }

A sample code to call the method looks like
self.alert("Warning", message: "The passcode is not correct, please try again", buttonTitle: "Ok",            handler: {(alert) in    println("ok pressed")})


No comments:

Post a Comment