Bird
Raised Fist0
iOS Swiftmobile~20 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of PreferenceKey in SwiftUI?
easy
A. To store user preferences permanently
B. To share simple data up the view hierarchy
C. To create custom buttons
D. To manage network requests

Solution

  1. Step 1: Understand PreferenceKey role

    PreferenceKey is designed to pass data from child views up to parent views in SwiftUI.
  2. Step 2: Differentiate from other uses

    It is not for permanent storage or UI elements but for sharing layout or state info upwards.
  3. Final Answer:

    To share simple data up the view hierarchy -> Option B
  4. Quick Check:

    PreferenceKey = share data up [OK]
Hint: PreferenceKey passes data upward, not stores or creates UI [OK]
Common Mistakes:
  • Confusing PreferenceKey with UserDefaults
  • Thinking it creates UI components
  • Assuming it manages network tasks
2. Which of the following is the correct way to declare a PreferenceKey with a default value of 0 and a reduce function that sums values?
easy
A. struct MyKey: PreferenceKey { static var defaultValue = 0; static func reduce(value: Int, nextValue: () -> Int) { value += nextValue() } }
B. struct MyKey: PreferenceKey { static let defaultValue = 0; static func reduce(value: Int, nextValue: () -> Int) { value += nextValue() } }
C. struct MyKey: PreferenceKey { var defaultValue: Int = 0; func reduce(value: inout Int, nextValue: () -> Int) { value += nextValue() } }
D. struct MyKey: PreferenceKey { static var defaultValue: Int = 0; static func reduce(value: inout Int, nextValue: () -> Int) { value += nextValue() } }

Solution

  1. Step 1: Check static defaultValue declaration

    It must be a static property with explicit type: static var defaultValue: Int = 0.
  2. Step 2: Verify reduce function signature

    Reduce must be static, take inout value, and add nextValue: static func reduce(value: inout Int, nextValue: () -> Int).
  3. Final Answer:

    struct MyKey: PreferenceKey { static var defaultValue: Int = 0; static func reduce(value: inout Int, nextValue: () -> Int) { value += nextValue() } } -> Option D
  4. Quick Check:

    Static defaultValue and reduce with inout = struct MyKey: PreferenceKey { static var defaultValue: Int = 0; static func reduce(value: inout Int, nextValue: () -> Int) { value += nextValue() } } [OK]
Hint: defaultValue and reduce must be static with correct signatures [OK]
Common Mistakes:
  • Missing static keyword on defaultValue or reduce
  • Using var instead of static var for defaultValue
  • Incorrect reduce function parameters
3. Given this code snippet, what will be printed?
struct CountKey: PreferenceKey {
  static var defaultValue = 0
  static func reduce(value: inout Int, nextValue: () -> Int) {
    value += nextValue()
  }
}

struct ContentView: View {
  var body: some View {
    VStack {
      Text("Hello").preference(key: CountKey.self, value: 1)
      Text("World").preference(key: CountKey.self, value: 2)
    }
    .onPreferenceChange(CountKey.self) { print($0) }
  }
}
medium
A. 3
B. 2
C. 1
D. 0

Solution

  1. Step 1: Understand preference values set

    Two Text views set preferences with values 1 and 2 respectively.
  2. Step 2: Apply reduce function logic

    Reduce sums values: 0 (default) + 1 + 2 = 3.
  3. Final Answer:

    3 -> Option A
  4. Quick Check:

    Sum of preferences = 3 [OK]
Hint: Reduce sums all values, so 1 + 2 = 3 [OK]
Common Mistakes:
  • Assuming only last value is used
  • Ignoring reduce function behavior
  • Confusing defaultValue with output
4. Identify the error in this PreferenceKey implementation:
struct SizeKey: PreferenceKey {
  static var defaultValue: CGSize = .zero
  static func reduce(value: CGSize, nextValue: () -> CGSize) {
    value = nextValue()
  }
}
medium
A. reduce function must have inout parameter for value
B. defaultValue must be non-static
C. nextValue must return Int, not CGSize
D. PreferenceKey cannot use CGSize type

Solution

  1. Step 1: Check defaultValue declaration

    defaultValue is correctly static with CGSize type.
  2. Step 2: Inspect reduce function signature

    Reduce must take inout for value to modify it, but here it is a value parameter.
  3. Final Answer:

    reduce function must have inout parameter for value -> Option A
  4. Quick Check:

    Reduce needs inout value parameter [OK]
Hint: Reduce must use inout for value to update it [OK]
Common Mistakes:
  • Forgetting inout keyword in reduce
  • Changing defaultValue to non-static
  • Wrong return type for nextValue
5. You want to pass the maximum width of child views up to a parent using PreferenceKey. Which implementation correctly combines widths to find the maximum?
hard
A. struct MaxWidthKey: PreferenceKey { static var defaultValue: CGFloat = 0 static func reduce(value: CGFloat, nextValue: () -> CGFloat) { value = max(value, nextValue()) } }
B. struct MaxWidthKey: PreferenceKey { static var defaultValue: CGFloat = 0 static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { value += nextValue() } }
C. struct MaxWidthKey: PreferenceKey { static var defaultValue: CGFloat = 0 static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { value = max(value, nextValue()) } }
D. struct MaxWidthKey: PreferenceKey { static var defaultValue: CGFloat = 0 static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { value = min(value, nextValue()) } }

Solution

  1. Step 1: Identify correct reduce logic for max

    To find maximum width, reduce must assign the max of current and next values.
  2. Step 2: Verify function signature and logic

    Reduce must be static, take inout value, and use value = max(value, nextValue()).
  3. Final Answer:

    struct MaxWidthKey: PreferenceKey { static var defaultValue: CGFloat = 0; static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { value = max(value, nextValue()) } } -> Option C
  4. Quick Check:

    Use max in reduce with inout value [OK]
Hint: Use max function and inout value in reduce [OK]
Common Mistakes:
  • Using sum (+) instead of max
  • Missing inout in reduce parameter
  • Using min instead of max
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