Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to pass empty closures in Swift

In Swift, I often have to pass a noop closure to a method just to comply with the method's expected parameters (arity). In the good old days of Obj C, one could pass nil for a noop callback and be done with it. Is there a quicker more elegant way to do that in Swift without passing an empty block like below?

UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in }) // do nothing in callback

Complete example:

import UIKit  class UIAlertControllerFactory {     class func ok(title: String, message: String) -> UIAlertController {         var alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)         var okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in         })         alertController.addAction(okAction)         return alertController     } } 
like image 233
dimroc Avatar asked Oct 04 '14 15:10

dimroc


People also ask

What is escaping closure in Swift?

An escaping closure is a closure that's called after the function it was passed to returns. In other words, it outlives the function it was passed to. A non-escaping closure is a closure that's called within the function it was passed into, i.e. before it returns.

How do you declare a closure in Swift?

Swift Closure Declaration Here, parameters - any value passed to closure. returnType - specifies the type of value returned by the closure. in (optional) - used to separate parameters/returnType from closure body.

What is the advantage of closure in Swift?

Closures can capture and store references to any constants and variables from the context in which they're defined. This is known as closing over those constants and variables. Swift handles all of the memory management of capturing for you. Don't worry if you aren't familiar with the concept of capturing.

Can a closure be assigned to a variable Swift?

How A Closure Works In Swift. Closures are self-contained blocks of functionality that can be passed around and used in your code. Said differently, a closure is a block of code that you can assign to a variable. You can then pass it around in your code, for instance to another function.


1 Answers

The general way, if you can't pass nil:

var okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,     handler:{ _ in }) 

You can also pass nil in this case, because (as of iOS 9.0) the handler is an Optional:

var okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,     handler:nil) 
like image 135
rob mayoff Avatar answered Oct 09 '22 04:10

rob mayoff