Skip to content
DeveloperMemos

How to Use Enums with @AppStorage in SwiftUI

SwiftUI, Enums, @AppStorage1 min read

The @AppStorage property wrapper is a useful feature introduced in SwiftUI. It allows developers to easily store and retrieve values from UserDefaults, which is a built-in storage system provided by Apple.

In this article, we'll explore how to use enums with @AppStorage to create type-safe and easily maintainable code.


Creating an Enum


Let's start by creating an enum that defines a set of options for our app. For this example, we'll create an enum called "Theme" that represents the different color schemes available to the user.

1enum Theme: String {
2 case light
3 case dark
4 case blue
5 case green
6}

Here, we define an enum with four cases that represent the different color schemes available to the user. The raw value of each case is a string, which is what we'll use to store and retrieve the value from UserDefaults.


Using @AppStorage


Now that we've defined our enum, we can use it with the @AppStorage property wrapper to store and retrieve the selected theme from UserDefaults.

1struct ContentView: View {
2 @AppStorage("theme") var selectedTheme: Theme = .light
3
4 var body: some View {
5 // Your view code here
6 }
7}

In this code, we're using @AppStorage to create a new property called "selectedTheme" that will be stored in UserDefaults under the key "theme". We're also providing a default value of .light, which is the initial value that will be used if no value is found in UserDefaults.


Updating the Selected Theme


Now that we have a property that stores the selected theme, we can use it to update the UI and allow the user to change the theme.

1struct ContentView: View {
2 @AppStorage("theme") var selectedTheme: Theme = .light
3
4 var body: some View {
5 VStack {
6 Picker("Theme", selection: $selectedTheme) {
7 Text("Light").tag(Theme.light)
8 Text("Dark").tag(Theme.dark)
9 Text("Blue").tag(Theme.blue)
10 Text("Green").tag(Theme.green)
11 }.pickerStyle(SegmentedPickerStyle())
12
13 // Your view code here
14 }
15 .preferredColorScheme(selectedTheme == .light ? .light : .dark)
16 }
17}

In this code, we're using a Picker to allow the user to select a new theme. We're binding the selectedTheme property to the Picker selection, which means that whenever the user selects a new theme, the selectedTheme property will be updated automatically.

We're also using the preferredColorScheme modifier to set the color scheme of the entire app based on the selected theme.