0
0
iOS Swiftmobile~20 mins

Preference keys in iOS Swift - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Settings Screen
This screen lets users toggle a setting that is saved using a preference key. The toggle state is remembered even after the app restarts.
Target UI
---------------------
|   Settings        |
|-------------------|
| Enable Notifications |
| [ ]               |
|                   |
---------------------
Add a toggle switch labeled 'Enable Notifications'.
Use UserDefaults to save the toggle state persistently.
Load the saved toggle state when the screen appears.
Update the saved state when the toggle changes.
Starter Code
iOS Swift
import SwiftUI

struct SettingsView: View {
    // TODO: Add @AppStorage property for preference key

    var body: some View {
        NavigationView {
            Form {
                Toggle("Enable Notifications", isOn: /* TODO: bind to preference key */)
            }
            .navigationTitle("Settings")
        }
    }
}

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

struct SettingsView: View {
    @AppStorage("enable_notifications") private var enableNotifications: Bool = false

    var body: some View {
        NavigationView {
            Form {
                Toggle("Enable Notifications", isOn: $enableNotifications)
            }
            .navigationTitle("Settings")
        }
    }
}

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

We use the @AppStorage property wrapper to connect a Boolean value to UserDefaults with the key "enable_notifications". This automatically saves and loads the toggle state. The Toggle control binds to this property, so when the user switches it on or off, the value updates and persists. When the screen loads, the toggle reflects the saved preference.

Final Result
Completed Screen
---------------------
|   Settings        |
|-------------------|
| Enable Notifications |
| [x]               |
|                   |
---------------------
User taps the toggle to turn notifications on or off.
The toggle state is saved immediately.
When the app restarts, the toggle shows the saved state.
Stretch Goal
Add a second toggle for 'Dark Mode' that also saves its state using a preference key.
💡 Hint
Use another @AppStorage property with a different key like "dark_mode_enabled" and bind it to a new Toggle.