Swift: Useful @autoclosure when presenting UIAlertViewController
There is an @autoclosure for that!
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.
