Swift: Useful @autoclosure when presenting UIAlertViewController

There is an @autoclosure for that!

Yevhen Dubinin
Jan 18, 2017 · 1 min read

To be honest, that was the first time I came up with @autoclosure usecase by myself. You know, this feeling: “Ha! There is an @autoclosure for that!”.

To respond to some UI events (e.g touching down a button), you could have a function like this:

dynamic func handleEditButton() {
editArticle()
}

After a while, it appears, that we now have to get the confirmation from user about his intension. The obvious way might be to present UIAlertViewControler with “Edit” and “Cancel” buttons. As now, you already have a function to do actual editing, wouldn’t it be nice to call it with the UIAlertViewControler's action callback?

Consider the declaration below:

func presentEditConfirmationDialog(onEdit: @escaping @autoclosure (Void)->Void, onCancel: @escaping @autoclosure (Void)->Void )

Having @autoclosure there, allows us to call (present the alert) and get the callbacks with this syntax:

self.presentApplyThemeDialog(onEdit: self.editArticle(), 
onCancel: () ) /* assuming you have nothing to do upon cancellation */

Notice, that we call the function by not wrapping it in a closure syntax. That’s how @autoclosure` works.

See the full Gist here.

Yevhen Dubinin

Written by

iOS Developer, Swiftwalker

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade