0
0
Swiftprogramming~20 mins

Optional declaration with ? suffix in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Optional Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
AOptional("Alice")
BAlice
Cnil
DError: Variable 'name' not initialized
Attempts:
2 left
💡 Hint
Remember that printing an optional variable shows it wrapped in Optional(...) if it has a value.
Predict Output
intermediate
2: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
AOptional(30)
Bnil
C30
DError: Cannot assign non-optional to optional
Attempts:
2 left
💡 Hint
Assigning a non-optional value to an optional variable wraps it automatically.
Predict Output
advanced
2: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
ASyntax error: Missing optional unwrapping
BNo error, total is 15
CRuntime error: nil value unwrapped
DType error: Cannot add 'Int?' and 'Int'
Attempts:
2 left
💡 Hint
You cannot directly add an optional Int and a non-optional Int without unwrapping.
🧠 Conceptual
advanced
2:00remaining
Which statement about optional declaration with '?' is true?
Choose the correct statement about declaring variables with '?' in Swift.
AVariables with '?' cannot be assigned nil after initialization.
BA variable declared with '?' must always have a value assigned.
CA variable declared with '?' can hold a value or nil.
DUsing '?' means the variable is a constant and cannot change.
Attempts:
2 left
💡 Hint
Think about what '?' means in Swift variable declarations.
Predict Output
expert
3: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")
AOptional(nil)
BNo pet
Cnil
DRuntime error: Unexpected nil
Attempts:
2 left
💡 Hint
Optional chaining returns nil if any part is nil, and the nil-coalescing operator provides a default.