← Back to archive

Development · SwiftUI

Saving preferences with @AppStorage

Connect UserDefaults to SwiftUI to persist simple settings and keep the interface in sync.

Read the Korean original on Velog ↗English translation

Development archive cover

Small preferences, such as a theme choice or whether onboarding is complete, should survive an app restart. @AppStorage connects key–value storage in UserDefaults to SwiftUI updates with a small declaration.

UserDefaults

UserDefaults stores simple settings and preferences as key–value pairs. Each value is associated with a key used to retrieve it later.

// Save the value
UserDefaults.standard.set(true, forKey: "isOnboardingShown")
UserDefaults.standard.set(10, forKey: "tapCount")
UserDefaults.standard.set("Snack", forKey: "userName")

// Read the value
let isOnboardingShown = UserDefaults.standard.bool(forKey: "isOnboardingShown") // true
let tapCount = UserDefaults.standard.integer(forKey: "tapCount") // 10
let userName = UserDefaults.standard.string(forKey: "userName") // "Snack"

Stored values remain available after the app closes.

struct AppStorageStudy: View {
    
    @State var currentUserName: String?
    
    var body: some View {
        VStack(spacing: 20) {
            Text(currentUserName ?? "DefaultName")
            Button("Save") {
            	// Data to persist
                let name: String = "Snack"
                currentUserName = name
                // Save the value with a key
                UserDefaults.standard.set(name, forKey: "userName")
            }
        }
        .onAppear {
        	// Read the value for this key
            currentUserName = UserDefaults.standard.string(forKey: "userName")
        }
    }
}

@AppStorage

Declare an @AppStorage property with a key to read and write a value through UserDefaults.

struct AppStorageStudy: View {
    // Save the value with a key
    @AppStorage("userName") var currentUserName: String?
    
    var body: some View {
        VStack(spacing: 20) {
            Text(currentUserName ?? "DefaultName")
            Button("Save") {
                let name: String = "Snack"
                currentUserName = name
            }
        }
    }
}

Changes to the property update the stored preference, and SwiftUI updates views that depend on it.

← Back to archive