Bird
0
0

Find the bug in this code:

medium📝 Debug Q7 of 15
iOS Swift - Local Data Persistence
Find the bug in this code:
let defaults = UserDefaults.standard
defaults.set(3.14, forKey: "pi")
let piValue = defaults.double(forKey: "pi")
print(piValue)
AKey "pi" must be declared before use
BNo bug; code works correctly
CMust cast value to Double when setting
Ddouble(forKey:) returns Int, not Double
Step-by-Step Solution
Solution:
  1. Step 1: Review saving and retrieving Double

    The code saves 3.14 as Double and retrieves it with double(forKey:).
  2. Step 2: Confirm no errors

    Both methods are correct and no casting or declaration is needed.
  3. Final Answer:

    No bug; code works correctly -> Option B
  4. Quick Check:

    Saving and reading Double works as shown [OK]
Quick Trick: double(forKey:) returns 0.0 if key missing, else saved Double [OK]
Common Mistakes:
  • Thinking casting is required
  • Expecting errors without reason
  • Assuming keys must be declared

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes