For the longest time, iOS developers have used AppDelegate
as the main entry point for their applications. With the launch of SwiftUI2 at WWDC 2020, Apple has introduced a new application life cycle that (almost) completely does away with AppDelegate
, making way for a DSL-like approach.
In this article, I’ll discuss why this change was introduced and how you can make use of the new life cycle in new or existing apps.
One of the first questions we need to answer is “How can we tell the compiler about the entry point to our application?” SE-0281 specifies how type-based program entry points work:
“The Swift compiler will recognize a type annotated with the
_@main_
attribute as providing the entry point for a program. Types marked with_@main_
have a single implicit requirement: declaring a static_main()_
method.”
When creating a new SwiftUI app, the app’s @main
class looks like this:
So where is the static main()
function that’s mentioned in SE-0281?
Well, it turns out that framework providers can (and should) provide a default implementation for their users’ convenience. Looking at the code snippet above, you’ll notice that SwiftUIAppLifeCycleApp
conforms to the App
protocol. Apple provides a protocol extension that looks like this:
And there we have it — this protocol extension provides a default implementation that takes care of the application startup.
Since the SwiftUI framework isn’t open source, we can’t see how Apple implemented this, but Swift Argument Parser is open source and uses this approach as well. Check out the source code for ParsableCommand
to see how they use a protocol extension to provide a default implementation of the static main
function that serves as the program entry point:
#swiftui #mobile #swift #programming #ios