Of Closures and Delegates


If you’ve been around Cocoa and Objective-C for any amount of time you are quite familiar with the delegate pattern.  You have also noticed that Swift also allows you to implement this same pattern.  And maybe when you were implementing a delegate pattern for a single-method protocol thought there must be a shorter way…
Don’t get me wrong, things like UITableViewController, AVFoundation, progress updates and the like that have several calls are well served by delegate methods.  But what about something that only does one thing like maybe a modal view controller that prompts for a username?  In these brief instances I like the clarity of providing a trailing closure in the presenting view controller:

func showModalView() {

modalView.onDataEntered = { [unowned self]

userName in

self.greetUser(userName: userName)





Of course closures can come with some memory management/ownership stuff as the [unowned self] reminds you and depending on the implementation you could go with [weak self] if there was a possibility of the caller not being there.  But for small, one-off situations I like having this option and the succinct implementation in the modal controller is at least in my opinion easy to follow:

class SomeModalView:UIViewController {

var userName:String?

var onDataEntered:((_ userName:String) -> ())?


func submitTapped() {

guard let uname = userName else { return }




Delegate methods are great when you have several different callbacks and make it clear in your code what is happening (tableViewCell selected, etc.).  As with most things in Swift there are lots of ways to create the same functionality and in the end a lot of this comes down to preference, but for just a single action I like the simplicity of being able to say “just do this one thing when this happens” without having to create a protocol for it (don’t tell Crusty).
Of Closures and Delegates

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s