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.
Practice
UserDefaults in an iOS app?Solution
Step 1: Understand UserDefaults role
UserDefaults is designed to save simple data like settings or preferences that stay saved even after the app closes.Step 2: Compare options
Options B, C, and D describe other app functions unrelated to UserDefaults.Final Answer:
To store small pieces of data that persist between app launches -> Option AQuick Check:
UserDefaults = persistent small data storage [OK]
- Thinking UserDefaults is for large databases
- Confusing UserDefaults with UI design
- Assuming UserDefaults handles networking
true for the key "isLoggedIn" using UserDefaults?Solution
Step 1: Recall UserDefaults saving syntax
The correct method to save a value isset(_:forKey:)called onUserDefaults.standard.Step 2: Match syntax with options
Only UserDefaults.standard.set(true, forKey: "isLoggedIn") uses the correct method and parameters.Final Answer:
UserDefaults.standard.set(true, forKey: "isLoggedIn") -> Option DQuick Check:
Save bool = set(_:forKey:) [OK]
- Omitting .standard before set
- Using wrong method names like save or store
- Swapping parameter labels
let defaults = UserDefaults.standard defaults.set(42, forKey: "score") let savedScore = defaults.integer(forKey: "score") print(savedScore)
Solution
Step 1: Understand saving and reading integer
The code saves integer 42 under key "score" and then reads it back usinginteger(forKey:).Step 2: Know integer(forKey:) behavior
This method returns the stored integer value or 0 if none exists. Since 42 was saved, it returns 42.Final Answer:
42 -> Option AQuick Check:
integer(forKey:) returns saved int or 0 [OK]
- Expecting Optional(42) instead of 42
- Confusing integer(forKey:) with object(forKey:)
- Thinking it returns nil if key missing
let defaults = UserDefaults.standard
defaults.set("John", forKey: "username")
let name = defaults.string(forKey: "user_name")
print(name ?? "No name")Solution
Step 1: Compare keys used for saving and reading
The string is saved with key "username" but read with key "user_name" which are different.Step 2: Understand impact of key mismatch
Because keys differ, reading returns nil and prints "No name" instead of "John".Final Answer:
The key used to save and read the string is different -> Option BQuick Check:
Matching keys needed for save/read [OK]
- Assuming UserDefaults can't save strings
- Forgetting .standard before set
- Misreading print statement syntax
Solution
Step 1: Save Boolean correctly
UserDefaults.standard.set(true, forKey: "darkMode") let isDark = UserDefaults.standard.bool(forKey: "darkMode") saves a Boolean true directly usingset(_:forKey:)with a Bool value.Step 2: Read Boolean safely with default
Usingbool(forKey:)returns the saved value or false if none exists, matching the requirement.Step 3: Analyze other options
UserDefaults.standard.set("true", forKey: "darkMode") let isDark = UserDefaults.standard.bool(forKey: "darkMode") saves a String "true" which is incorrect for bool reading. UserDefaults.standard.set(true, forKey: "darkMode") let isDark = UserDefaults.standard.object(forKey: "darkMode") as? Bool ?? false uses object casting which fails because NSNumber(true) as? Bool returns nil, so ?? false gives false even when set to true. UserDefaults.standard.set(true, forKey: "darkMode") let isDark = UserDefaults.standard.string(forKey: "darkMode") == "true" reads as String and compares, but string(forKey:) returns nil for NSNumber causing false.Final Answer:
UserDefaults.standard.set(true, forKey: "darkMode") let isDark = UserDefaults.standard.bool(forKey: "darkMode") -> Option CQuick Check:
Save/read Bool with set and bool(forKey:) [OK]
- Saving Bool as String and reading as Bool
- Using object(forKey:) cast instead of bool(forKey:)
- Reading Bool as String and comparing
Ready to prove it?
Pass the test and this pattern moves unknown
