Swift snippet #14 โ€” UIAlertControllerStyle

Ritesh Gupta
Swift Snippets ๐Ÿš€
2 min readNov 9, 2017


Thursday, 9th November, 2017


My last snippet was about how we can transform Appleโ€™s Foundation/UIKit apis using extension to remove some of the boilerplate code. Today we will explore how we can reduce code to construct a UIAlertController.

You can find its Gist here!


The first extension is on UIAlertControllerStyle which returns an instance of UIAlertController of a specific style i.e. โ€“โ€“ alert or actionSheet. So now I can do something like this,

let alertController = UIAlertControllerStyle
.controller(title:, message:, actions:)

So instead of passing a style type inside the constructor of UIAlertController, I can now ask for a controller of a particular style (if you have read my earlier snippets or blog posts, you probably know by now that I like extension oriented apis โ€“โ€“ looks cleaner and simple to read).


Now any alert will also have some actions associated to it. Thus the next extension is on String since every action will some have title and it returns an instance of UIAlertAction,

let dismissAction = "Dismiss".alertAction()let retryAction = "Retry".alertAction { _ in /* retry logic */ }

So instead of passing a title into the constructor of UIAlertAction, I can now ask of an alertAction on a String.

Thatโ€™s it, now letโ€™s look at the entire api,

Without creating extra classes, we have been able to write such a short api to construct any kind of UIAlertController. You can also make an actionSheet using the same api ๐Ÿš€.

PS โ€“โ€“ I have used String for simplicity but if you donโ€™t like it then you can also create an Enum just for the different actions and extend it to have similar behaviour!

If you are wondering about the inception of Swift-Snippets or want to checkout more such snippets, you can find them here ๐Ÿ˜Š