Challenge - 5 Problems
UserDefaults Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ ui_behavior
intermediate1:30remaining
What is the output after saving and retrieving a value with UserDefaults?
Consider this Swift code that saves a string to UserDefaults and then retrieves it. What will be printed?
iOS Swift
let defaults = UserDefaults.standard let key = "username" defaults.set("Alice", forKey: key) if let name = defaults.string(forKey: key) { print(name) } else { print("No value") }
Attempts:
2 left
💡 Hint
UserDefaults stores simple values persistently and can retrieve them by the same key.
✗ Incorrect
The code saves the string "Alice" under the key "username" and then retrieves it successfully, so it prints "Alice".
📝 Syntax
intermediate1:30remaining
Which option correctly saves an integer to UserDefaults?
You want to save the integer 42 to UserDefaults under the key "score". Which code snippet does this correctly?
Attempts:
2 left
💡 Hint
Use the standard UserDefaults instance and the set(_:forKey:) method.
✗ Incorrect
Option D uses the correct method and instance to save an integer value to UserDefaults.
❓ lifecycle
advanced2:00remaining
When are UserDefaults values saved to disk?
You save a value to UserDefaults using set(_:forKey:). When is this value guaranteed to be saved to disk?
Attempts:
2 left
💡 Hint
UserDefaults batches writes for efficiency and saves at certain app lifecycle events.
✗ Incorrect
UserDefaults automatically saves changes when the app goes to background or terminates. The synchronize() method is deprecated and not needed.
🔧 Debug
advanced2:00remaining
Why does retrieving a saved Bool from UserDefaults return false unexpectedly?
This code saves a Bool value true but later retrieving it returns false. What is the likely cause?
let defaults = UserDefaults.standard
defaults.set(true, forKey: "isLoggedIn")
let loggedIn = defaults.bool(forKey: "isLoggedIn")
print(loggedIn)
Attempts:
2 left
💡 Hint
Check if the key exists before relying on bool(forKey:).
✗ Incorrect
bool(forKey:) returns false if the key does not exist, so if the value was not saved or the key is wrong, it returns false by default.
🧠 Conceptual
expert2:30remaining
What is the best practice for storing sensitive data in UserDefaults?
You want to store a user's password securely. Which statement is true about storing it in UserDefaults?
Attempts:
2 left
💡 Hint
Think about data encryption and security best practices on iOS.
✗ Incorrect
UserDefaults stores data in plain text and is not encrypted. Sensitive data like passwords should be stored in the Keychain, which is designed for secure storage.