Bird
0
0

What is wrong with this Swift code for saving and retrieving a color string?

medium📝 Debug Q6 of 15
iOS Swift - Local Data Persistence
What is wrong with this Swift code for saving and retrieving a color string?
UserDefaults.standard.setValue("blue", forKey: "color")
let color = UserDefaults.standard.string(forKey: "color")
print(color!)
AUsing setValue instead of set may cause unexpected behavior
BThe key "color" should be an integer
CForce unwrapping color with '!' can cause a crash if nil
DUserDefaults cannot store strings
Step-by-Step Solution
Solution:
  1. Step 1: Analyze setValue usage

    setValue works but set is preferred; not an error here.
  2. Step 2: Check key type

    Keys must be strings, so "color" is correct.
  3. Step 3: Identify force unwrap risk

    Using 'color!' can crash if the value is nil.
  4. Final Answer:

    Force unwrapping color with '!' can cause a crash if nil -> Option C
  5. Quick Check:

    Avoid force unwrapping optional values [OK]
Quick Trick: Never force unwrap optionals without checking [OK]
Common Mistakes:
  • Assuming setValue is incorrect
  • Thinking keys must be integers
  • Believing UserDefaults can't store strings

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes