Bird
Raised Fist0
iOS Swiftmobile~20 mins

UserDefaults for simple values in iOS Swift - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Settings Screen
A screen where the user can toggle a switch and enter their name. The app saves these values using UserDefaults so they stay saved when the app restarts.
Target UI
-------------------------
| Settings              |
|-----------------------|
| Name: [___________]   |
|                       |
| Enable Notifications:  |
| [  Switch  ]          |
|                       |
| [ Save ]              |
-------------------------
A TextField to enter the user's name
A Switch to toggle notifications on or off
A Save button that saves the name and switch state to UserDefaults
When the screen loads, it should read saved values from UserDefaults and update the UI
Use UserDefaults.standard for saving and loading
Starter Code
iOS Swift
import SwiftUI

struct SettingsView: View {
    @State private var name: String = ""
    @State private var notificationsEnabled: Bool = false

    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("User Info")) {
                    TextField("Enter your name", text: $name)
                }
                Section(header: Text("Preferences")) {
                    Toggle(isOn: $notificationsEnabled) {
                        Text("Enable Notifications")
                    }
                }
                Button("Save") {
                    // TODO: Save name and notificationsEnabled to UserDefaults
                }
            }
            .navigationTitle("Settings")
            // TODO: Load saved values from UserDefaults when view appears
        }
    }
}

struct SettingsView_Previews: PreviewProvider {
    static var previews: some View {
        SettingsView()
    }
}
Task 1
Task 2
Solution
iOS Swift
import SwiftUI

struct SettingsView: View {
    @State private var name: String = ""
    @State private var notificationsEnabled: Bool = false

    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("User Info")) {
                    TextField("Enter your name", text: $name)
                }
                Section(header: Text("Preferences")) {
                    Toggle(isOn: $notificationsEnabled) {
                        Text("Enable Notifications")
                    }
                }
                Button("Save") {
                    UserDefaults.standard.set(name, forKey: "userName")
                    UserDefaults.standard.set(notificationsEnabled, forKey: "notificationsEnabled")
                }
            }
            .navigationTitle("Settings")
            .onAppear {
                if let savedName = UserDefaults.standard.string(forKey: "userName") {
                    name = savedName
                }
                notificationsEnabled = UserDefaults.standard.bool(forKey: "notificationsEnabled")
            }
        }
    }
}

struct SettingsView_Previews: PreviewProvider {
    static var previews: some View {
        SettingsView()
    }
}

This solution uses UserDefaults.standard to save and load simple values.

When the Save button is tapped, it saves the current name string and notificationsEnabled boolean to UserDefaults with keys "userName" and "notificationsEnabled".

When the view appears, it reads these values back from UserDefaults. If a saved name exists, it updates the name state. It also reads the boolean for notifications, defaulting to false if not set.

This way, the user's settings persist between app launches, and the UI always shows the saved values.

Final Result
Completed Screen
-------------------------
| Settings              |
|-----------------------|
| Name: [John Doe   ]   |
|                       |
| Enable Notifications:  |
| [  ON Switch  ]       |
|                       |
| [ Save ]              |
-------------------------
User types their name in the text field
User toggles the switch on or off
User taps Save to store the values
When the screen opens again, the saved name and switch state appear automatically
Stretch Goal
Add a Reset button that clears the saved name and notifications setting from UserDefaults and resets the UI to default values.
💡 Hint
Use UserDefaults.standard.removeObject(forKey:) for each saved key and reset the @State variables to default values.

Practice

(1/5)
1. What is the main purpose of UserDefaults in an iOS app?
easy
A. To store small pieces of data that persist between app launches
B. To create complex database structures
C. To handle network requests
D. To design the app's user interface

Solution

  1. Step 1: Understand UserDefaults role

    UserDefaults is designed to save simple data like settings or preferences that stay saved even after the app closes.
  2. Step 2: Compare options

    Options B, C, and D describe other app functions unrelated to UserDefaults.
  3. Final Answer:

    To store small pieces of data that persist between app launches -> Option A
  4. Quick Check:

    UserDefaults = persistent small data storage [OK]
Hint: Remember UserDefaults saves simple data persistently [OK]
Common Mistakes:
  • Thinking UserDefaults is for large databases
  • Confusing UserDefaults with UI design
  • Assuming UserDefaults handles networking
2. Which of the following is the correct syntax to save a Boolean value true for the key "isLoggedIn" using UserDefaults?
easy
A. UserDefaults.standard.save(true, "isLoggedIn")
B. UserDefaults.set(true, key: "isLoggedIn")
C. UserDefaults.standard.store(true, forKey: "isLoggedIn")
D. UserDefaults.standard.set(true, forKey: "isLoggedIn")

Solution

  1. Step 1: Recall UserDefaults saving syntax

    The correct method to save a value is set(_:forKey:) called on UserDefaults.standard.
  2. Step 2: Match syntax with options

    Only UserDefaults.standard.set(true, forKey: "isLoggedIn") uses the correct method and parameters.
  3. Final Answer:

    UserDefaults.standard.set(true, forKey: "isLoggedIn") -> Option D
  4. Quick Check:

    Save bool = set(_:forKey:) [OK]
Hint: Use UserDefaults.standard.set(value, forKey: key) to save [OK]
Common Mistakes:
  • Omitting .standard before set
  • Using wrong method names like save or store
  • Swapping parameter labels
3. What will be the output of this Swift code snippet?
let defaults = UserDefaults.standard
defaults.set(42, forKey: "score")
let savedScore = defaults.integer(forKey: "score")
print(savedScore)
medium
A. 42
B. Optional(42)
C. nil
D. 0

Solution

  1. Step 1: Understand saving and reading integer

    The code saves integer 42 under key "score" and then reads it back using integer(forKey:).
  2. 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.
  3. Final Answer:

    42 -> Option A
  4. Quick Check:

    integer(forKey:) returns saved int or 0 [OK]
Hint: integer(forKey:) returns Int, not Optional [OK]
Common Mistakes:
  • Expecting Optional(42) instead of 42
  • Confusing integer(forKey:) with object(forKey:)
  • Thinking it returns nil if key missing
4. Identify the error in this code snippet that tries to save a string to UserDefaults:
let defaults = UserDefaults.standard
defaults.set("John", forKey: "username")
let name = defaults.string(forKey: "user_name")
print(name ?? "No name")
medium
A. The print statement syntax is incorrect
B. The key used to save and read the string is different
C. The set method is missing .standard
D. UserDefaults cannot save strings

Solution

  1. 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.
  2. Step 2: Understand impact of key mismatch

    Because keys differ, reading returns nil and prints "No name" instead of "John".
  3. Final Answer:

    The key used to save and read the string is different -> Option B
  4. Quick Check:

    Matching keys needed for save/read [OK]
Hint: Check keys match exactly when saving and reading [OK]
Common Mistakes:
  • Assuming UserDefaults can't save strings
  • Forgetting .standard before set
  • Misreading print statement syntax
5. You want to save a user's preferred theme setting as a Boolean in UserDefaults and then read it safely with a default of false if not set. Which code snippet correctly does this?
hard
A. UserDefaults.standard.set(true, forKey: "darkMode") let isDark = UserDefaults.standard.object(forKey: "darkMode") as? Bool ?? false
B. UserDefaults.standard.set("true", forKey: "darkMode") let isDark = UserDefaults.standard.bool(forKey: "darkMode")
C. UserDefaults.standard.set(true, forKey: "darkMode") let isDark = UserDefaults.standard.bool(forKey: "darkMode")
D. UserDefaults.standard.set(true, forKey: "darkMode") let isDark = UserDefaults.standard.string(forKey: "darkMode") == "true"

Solution

  1. Step 1: Save Boolean correctly

    UserDefaults.standard.set(true, forKey: "darkMode") let isDark = UserDefaults.standard.bool(forKey: "darkMode") saves a Boolean true directly using set(_:forKey:) with a Bool value.
  2. Step 2: Read Boolean safely with default

    Using bool(forKey:) returns the saved value or false if none exists, matching the requirement.
  3. 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.
  4. Final Answer:

    UserDefaults.standard.set(true, forKey: "darkMode") let isDark = UserDefaults.standard.bool(forKey: "darkMode") -> Option C
  5. Quick Check:

    Save/read Bool with set and bool(forKey:) [OK]
Hint: Use bool(forKey:) to read Bool with default false [OK]
Common Mistakes:
  • Saving Bool as String and reading as Bool
  • Using object(forKey:) cast instead of bool(forKey:)
  • Reading Bool as String and comparing
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard