Swift snippet #14 โ UIAlertControllerStyle
Thursday, 9th November, 2017
About
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!
UIAlertControllerStyle
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
.alert
.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).
String
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 ๐