Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to save a string value to UserDefaults using the key "username".
iOS Swift
UserDefaults.standard.set("John", forKey: [1])
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a key with underscores instead of the exact key.
Forgetting to put the key in quotes.
✗ Incorrect
The key must exactly match "username" to store the value correctly.
2fill in blank
mediumComplete the code to retrieve a boolean preference with key "isDarkMode" from UserDefaults.
iOS Swift
let darkModeEnabled = UserDefaults.standard.[1]("isDarkMode")
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using string(forKey:) when expecting a boolean.
Using integer(forKey:) or double(forKey:) incorrectly.
✗ Incorrect
Use bool(forKey:) to get a boolean value from UserDefaults.
3fill in blank
hardFix the error in the code to remove a preference with key "userAge" from UserDefaults.
iOS Swift
UserDefaults.standard.[1](forKey: "userAge")
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using deleteObject or clearObject which do not exist.
Using set(nil, forKey:) which is not recommended.
✗ Incorrect
The correct method to remove a value is removeObject(forKey:).
4fill in blank
hardFill both blanks to save an integer preference "launchCount" incremented by 1.
iOS Swift
let count = UserDefaults.standard.[1]("launchCount") UserDefaults.standard.set(count [2] 1, forKey: "launchCount")
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using double(forKey:) instead of integer(forKey:).
Using - instead of + to increment.
✗ Incorrect
Retrieve the integer value with integer(forKey:) and add 1 to increment.
5fill in blank
hardFill all three blanks to create a dictionary preference with keys "theme", "fontSize", and "notifications".
iOS Swift
let settings: [String: Any] = ["theme": [1], "fontSize": [2], "notifications": [3]] UserDefaults.standard.set(settings, forKey: "userSettings")
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using quotes incorrectly around numbers or booleans.
Mixing up the order of values.
✗ Incorrect
The theme is a string "dark", fontSize is integer 14, notifications is boolean true.