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.

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…

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

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