Challenge - 5 Problems
Swift Optional Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Swift code with optional?
Consider the following Swift code. What will be printed when it runs?
Swift
var name: String? = "Alice" print(name)
Attempts:
2 left
💡 Hint
Remember that printing an optional variable shows it wrapped in Optional(...) if it has a value.
✗ Incorrect
In Swift, an optional variable holds either a value or nil. Printing an optional directly shows Optional(value) if it has a value.
❓ Predict Output
intermediate2:00remaining
What is the value of 'age' after this code runs?
Look at this Swift code snippet. What is the value of 'age' after execution?
Swift
var age: Int? = nil age = 30
Attempts:
2 left
💡 Hint
Assigning a non-optional value to an optional variable wraps it automatically.
✗ Incorrect
Assigning 30 to 'age' wraps it as Optional(30). The variable 'age' is still optional but holds the value 30.
❓ Predict Output
advanced2:00remaining
What error does this code produce?
What error will this Swift code cause when compiled?
Swift
var score: Int? = 10 var total: Int = score + 5
Attempts:
2 left
💡 Hint
You cannot directly add an optional Int and a non-optional Int without unwrapping.
✗ Incorrect
The compiler does not allow adding an optional Int and an Int directly. You must unwrap the optional first.
🧠 Conceptual
advanced2:00remaining
Which statement about optional declaration with '?' is true?
Choose the correct statement about declaring variables with '?' in Swift.
Attempts:
2 left
💡 Hint
Think about what '?' means in Swift variable declarations.
✗ Incorrect
The '?' suffix means the variable is optional and can hold a value or nil.
❓ Predict Output
expert3:00remaining
What is the output of this Swift optional chaining code?
Analyze the code and select the output printed.
Swift
class Person { var pet: Pet? } class Pet { var name: String init(name: String) { self.name = name } } let person = Person() print(person.pet?.name ?? "No pet")
Attempts:
2 left
💡 Hint
Optional chaining returns nil if any part is nil, and the nil-coalescing operator provides a default.
✗ Incorrect
Since 'person.pet' is nil, 'person.pet?.name' is nil, so the default "No pet" is printed.