Bird
0
0

Given this code:

hard📝 Application Q9 of 15
Swift - Optionals
Given this code:
var optionalString: String? = "Swift"
var forcedString: String = optionalString!
What is the danger if optionalString is later set to nil and forcedString is accessed?
ARuntime crash when accessing forcedString
BCompiler error on assignment
CforcedString becomes nil automatically
DNo danger, forcedString is a non-optional copy
Step-by-Step Solution
Solution:
  1. Step 1: Understand force unwrap assignment

    Force unwrapping copies the value inside optional to a non-optional variable.
  2. Step 2: Effect of changing original optional later

    Changing optionalString to nil does not affect forcedString which holds a separate value.
  3. Final Answer:

    No danger, forcedString is a non-optional copy -> No danger, forcedString is a non-optional copy
  4. Quick Check:

    Force unwrap copies value, later nil optional safe [OK]
Quick Trick: Force unwrap copies value; later nil optional won't crash [OK]
Common Mistakes:
  • Thinking forcedString depends on optionalString after assignment
  • Expecting runtime crash on forcedString access
  • Confusing optional and non-optional variables

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes