@main, App, Scene, WindowGroupThese are the lesson notes for this day. Its build-along tutorial and flash cards have not been written yet.
@main, App, Scene, WindowGroup@main marks the one type that is the program's entry point. It is a Swift feature, not a SwiftUI one, and a target can have only one. In a SwiftUI app that type conforms to App, and its body returns one or more scenes. A Scene is SwiftUI's version of UIScene: a unit of user interface whose lifecycle the system manages. WindowGroup is the scene you will use most. On iPhone it is the app's single window. On iPad and Mac the user can open several windows from it, and each window gets its own copy of the root view and that view's state.
Lifecycle events arrive as data rather than as delegate callbacks: read @Environment(\.scenePhase) instead of implementing sceneDidEnterBackground. If a library still needs an app delegate, you attach one with @UIApplicationDelegateAdaptor. Document-based apps use DocumentGroup, and iOS 27 adds new document protocols (ReadableDocument, WritableDocument).
@main
struct MyApp: App {
@Environment(\.scenePhase) private var scenePhase
var body: some Scene {
WindowGroup { // one window on iPhone; many on iPad and Mac
ContentView()
}
.onChange(of: scenePhase) { _, phase in
print("scene is now \(phase)") // active, inactive, or background
}
}
}
Exercise
In a new project, follow the path from @main to the first Text on screen. Add the onChange(of: scenePhase) shown above, then send the app to the background and bring it back, and watch what is printed.
@main do, and how many can one target have?Scene, and which UIKit concept does it correspond to?@State when the user opens a second window?