Swift snippet #14 โ€” UIAlertControllerStyle

Ritesh Gupta
Nov 9, 2017 ยท 2 min read

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.


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 ๐Ÿ˜Š

Swift Snippets ๐Ÿš€

Itโ€™s an initiative to share snippets that leverages theโ€ฆ

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and youโ€™ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer โ€” welcome home. Itโ€™s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store