< How to control which view is shown when your app launches | How to add an AppDelegate to a SwiftUI app > |
Updated for Xcode 14.2
When you’re using the SwiftUI App life cycle, your app launches through one struct that conforms to the App
protocol. Its job is to create your initial view using either WindowGroup
, DocumentGroup
, or similar, but because its created before any of your actual views this is the perfect place for running code when your app launches.
For example, if you wanted to set up some initial UserDefaults
values, your app’s initializer is a great place to call register(defaults:)
. This method sets up default defaults, by which I mean initial values for UserDefaults
values that exist only until you set them – as soon as you provide a value of your own, these aren’t used any more, and these initial values also disappear when your app is terminated so you should call it every launch just to make sure.
So, we might write something like this:
@main
struct ExampleApp: App {
// register initial UserDefaults values every launch
init() {
UserDefaults.standard.register(defaults: [
"name": "Taylor Swift",
"highScore": 10
])
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
That initializer() is run before the body
property is called, so it’s also before ContentView
is called. As a result, any places where you read UserDefaults
in ContentView
will already have your defaults in place.
To demonstrate this, here’s an example ContentView
struct that uses @AppStorage
to read the “name” key:
struct ContentView: View {
@AppStorage("name") var name = "Anonymous"
var body: some View {
Text("Your name is \(name).")
}
}
Download this as an Xcode project
Using @AppStorage
requires that we give our property an initial value, which is cumbersome because we need to ensure we have the same initial value everywhere the property is used.
However, here it doesn’t matter: “Anonymous” will only be used for times when no value exists, and no initial defaults have been registered. We already called register(defaults:)
in our app’s initializer, so this view will show “Your name is Taylor Swift.”
SPONSORED Thorough mobile testing hasn’t been efficient testing. With Waldo Sessions, it can be! Test early, test often, test directly in your browser and share the replay with your team.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.