Challenge - 5 Problems
Swift IUO Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of accessing an implicitly unwrapped optional
What is the output of this Swift code?
Swift
var name: String! = "Alice" print(name.count)
Attempts:
2 left
💡 Hint
Implicitly unwrapped optionals can be used like normal values without unwrapping.
✗ Incorrect
The variable 'name' is an implicitly unwrapped optional containing "Alice". Accessing 'name.count' works like a normal String, so it prints 5.
❓ Predict Output
intermediate2:00remaining
Behavior when implicitly unwrapped optional is nil
What happens when you run this Swift code?
Swift
var number: Int! = nil print(number + 1)
Attempts:
2 left
💡 Hint
Implicitly unwrapped optionals behave like normal values but crash if nil.
✗ Incorrect
Since 'number' is nil, trying to use it as a normal Int causes a runtime crash due to forced unwrapping of nil.
🔧 Debug
advanced3:00remaining
Identify the cause of runtime crash with implicitly unwrapped optional
Why does this Swift code crash at runtime?
Swift
class Person { var pet: String! func printPet() { print(pet.uppercased()) } } let p = Person() p.printPet()
Attempts:
2 left
💡 Hint
Implicitly unwrapped optionals crash if nil when accessed.
✗ Incorrect
The 'pet' property is implicitly unwrapped optional but is never assigned a value, so it is nil. Accessing 'pet.uppercased()' forces unwrapping nil, causing a runtime crash.
🧠 Conceptual
advanced2:30remaining
Understanding implicitly unwrapped optional declaration
Which statement about implicitly unwrapped optionals in Swift is true?
Attempts:
2 left
💡 Hint
Think about how implicitly unwrapped optionals behave differently from normal optionals.
✗ Incorrect
Implicitly unwrapped optionals can be used like normal values without explicit unwrapping, but if they are nil when accessed, the program crashes at runtime.
❓ Predict Output
expert3:00remaining
Output of chained implicitly unwrapped optionals
What is the output of this Swift code?
Swift
class Node { var value: Int var next: Node! init(_ value: Int) { self.value = value } } let first = Node(1) let second = Node(2) first.next = second second.next = nil print(first.next.next.value)
Attempts:
2 left
💡 Hint
Consider what happens when accessing 'next' of a nil implicitly unwrapped optional.
✗ Incorrect
The 'second.next' is nil. Accessing 'first.next.next.value' tries to access 'next' of nil, causing a runtime crash due to forced unwrapping of nil.