UserDefaults lets your app save small pieces of information like settings or preferences. This way, the app remembers them even after you close it.
UserDefaults for simple values in iOS Swift
let defaults = UserDefaults.standard // Save a value defaults.set(value, forKey: "key") // Read a value let value = defaults.value(forKey: "key")
Use set(_:forKey:) to save values like strings, numbers, or booleans.
Use value(forKey:) or typed methods like string(forKey:) to read values.
let defaults = UserDefaults.standard defaults.set(true, forKey: "hasSeenWelcome") let seen = defaults.bool(forKey: "hasSeenWelcome")
let defaults = UserDefaults.standard defaults.set("John", forKey: "username") let name = defaults.string(forKey: "username")
let defaults = UserDefaults.standard defaults.set(42, forKey: "launchCount") let count = defaults.integer(forKey: "launchCount")
This app shows a welcome message. The first time you open it, it shows "Welcome for the first time!" with a button. When you tap the button, it saves that you have seen the welcome. Next time you open the app, it shows "Welcome back!" because it reads the saved value.
import SwiftUI struct ContentView: View { @State private var hasSeenWelcome = UserDefaults.standard.bool(forKey: "hasSeenWelcome") var body: some View { VStack(spacing: 20) { if hasSeenWelcome { Text("Welcome back!") } else { Text("Welcome for the first time!") Button("Got it") { hasSeenWelcome = true UserDefaults.standard.set(true, forKey: "hasSeenWelcome") } } } .padding() } } @main struct MyApp: App { var body: some Scene { WindowGroup { ContentView() } } }
UserDefaults is good for small, simple data only. Don't use it for big files or sensitive info.
Always use the same key string to save and read the value.
Changes to UserDefaults are saved immediately, so no extra saving step is needed.
UserDefaults stores small pieces of data that your app can remember between launches.
Use set(_:forKey:) to save and typed methods like bool(forKey:) to read.
Good for simple settings like toggles, counters, or user names.