Excursus: SwiftUI App Hierarchy

With the release of Xcode 12 in 2020, the functionality of SwiftUI has been greatly expanded, and the framework has been significantly improved.

One of the newly introduced features is the “App” framework and lifecycle that was added to SwiftUI. Since then it is possible to build apps entirely with SwiftUI.

We can catch a glimpse of the AppAPI functionality by selecting the SwiftUIStarterApp.swift file in the Project Navigator. Whenever you create a new SwiftUI project in Xcode, Xcode always automatically generates a file named “*YourAppName*App.swift”.

The code inside this file should look like this:

import SwiftUI

@main
struct SwiftUIStarterApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

What is this all about? Well, with the new SwiftUI update, Apple introduced a reworked app hierarchy concept, including new APIs like App and Scene.

Let’s try to explain this new concept as concisely as possible.

As you already know, everything you see on the screen of your app is in some way defined by a View. The more complex your app’s interface gets, the more nested Views you create, resulting in less or more complex view hierarchies. 

Certain areas of visible Views can be divided into distinct regions. With the new SwiftUI update, we refer to those areas as ScenesScenes always consist of one or multiple Views, and there are various types of Scenes, such as WindowGroup or DocumentGroup.

Throughout this book, we will only work with the WindowGroup scene. But when it comes to developing SwiftUI, iPadOS and macOS apps, other scene types can get interesting.

All Scenes together form the entire content for our App. An App itself contains Scenes that conclude in the following hierarchy structure of any SwiftUI app.

With this knowledge, you should grasp the rough concept when looking at the default code in your YourProjectApp.swift file. The highest piece in the hierarchy is the App, which returns Scenes, which in turn return Views.

The @main keyword indicates that this struct should be used to launch the app. In our case, our app would launch a ContentView instance in a WindowGroup scene.

Of course, there is much more to know about this. However, this should be enough knowledge for you to start developing iOS apps with SwiftUI.

Leave a Reply

Your email address will not be published. Required fields are marked *