Bird
0
0

Find the mistake in this Swift code that attempts to save a Double value:

medium📝 Debug Q6 of 15
iOS Swift - Local Data Persistence
Find the mistake in this Swift code that attempts to save a Double value:
let defaults = UserDefaults.standard
defaults.set(3.14, forKeyName: "pi")
let piValue = defaults.double(forKey: "pi")
Adouble(forKey:) returns an optional and must be unwrapped
BUserDefaults cannot store Double values
CThe key "pi" must be declared as a constant
DThe method parameter should be 'forKey', not 'forKeyName'
Step-by-Step Solution
Solution:
  1. Step 1: Check method signature

    The correct method to set a value in UserDefaults is set(_:forKey:), not set(_:forKeyName:).
  2. Step 2: Identify the error

    Using 'forKeyName' causes a compile-time error because the method does not exist.
  3. Step 3: Correct usage

    Change to defaults.set(3.14, forKey: "pi") to fix the error.
  4. Final Answer:

    The method parameter should be 'forKey', not 'forKeyName' -> Option D
  5. Quick Check:

    Verify method signatures in documentation [OK]
Quick Trick: Use 'forKey' parameter name when setting values [OK]
Common Mistakes:
  • Using incorrect parameter names
  • Assuming UserDefaults can't store Double
  • Confusing optional return types

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More iOS Swift Quizzes