[Dev Diaries] CRToastSwift
TL;DR: Grab the code here
I was looking into using Swift Package Manager for iOS to try out the new features From The Future, and I happened to have a UI/UX concept with alerts (you Android people would call them toasts) that I wanted to formalize a bit and it reminded me of a piece of code I used on past projects that resonated : CRToast. It's not that this code was doing something uber exciting or fantastical. Just that there was so much care and deliberation in the code style.
I decided it was the perfect candidate for a somewhat long haul Swift project that would involve many tricks, some head scratching, and a decent amount of care to do it justice.
First things first, all of the 🤬 options that are available (plus one I will detail later). The original is 1619 lines of Objective-C code (including comments). After a naive one-to-one Swift port, the result is a thousand or so lines of Swift code (including the same comments). Take that people who say that Objective-C isn't more verbose. I'm fairly sure I can whittle it down some more because half of the helper functions aren't actually that useful once you have the built-in correctness checker of Swift. But, that's only step one, and decidedly naive at that. Similarly toast controller and window got cut in half length-wise, despite the fact I had to add a new function to make up for deprecation.
I love Objective-C, especially the fact that it will let me do whatever I want with memory management, swizzling and sending whatever message I want to whatever object (although the last one has been severely reprimanded since 2.0), but there's not denying that it's way less safe and explicit than Swift, making it a much worse language for beginners. In fact I remember remarking the same about Java vs C in the prehistoric times.
One of the two pièce-de-résistance in the code is the
layoutSubviews part for the toast view itself. Given the huge amount of options, taking all the cases in account is a marathon (all things being relative, it's only 100 lines of code). The other one is the entirety of
CRToastManager whose job it is to expose only a few dedicated functions for the whole thing.
The one feature I wanted to add is something I worked on but wasn't ultimately used in a past project: Alerts tend to be ignored and dismissed a few times before the users kind of realize the on-screen items they are related to. One idea to call the attention on them is to use
UIKitDynamics to let the alerts fall unmolested when there's nothing related in the view, but have them bounce of important stuff otherwise:
So, here it is: CRToastSwift with callouts!