0
0
iOS Swiftmobile~20 mins

Optionals and unwrapping in iOS Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Swift Optionals Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
📝 Syntax
intermediate
2:00remaining
What is the output of this Swift code with optional binding?
Consider this Swift code snippet that uses optional binding to unwrap an optional string. What will be printed?
iOS Swift
let optionalName: String? = "Alice"
if let name = optionalName {
  print("Hello, \(name)!")
} else {
  print("No name found.")
}
ANo name found.
BHello, Alice!
COptional("Alice")
DCompilation error
Attempts:
2 left
💡 Hint
Optional binding safely unwraps the optional if it contains a value.
ui_behavior
intermediate
2:00remaining
What happens when force unwrapping a nil optional?
Given this Swift code, what will happen when it runs?
iOS Swift
let optionalNumber: Int? = nil
let number = optionalNumber!
print(number)
ARuntime crash with fatal error: unexpectedly found nil while unwrapping an Optional value
BPrints nil
CPrints 0
DCompilation error
Attempts:
2 left
💡 Hint
Force unwrapping nil optionals causes a runtime crash.
🧠 Conceptual
advanced
2:00remaining
What is the value of 'result' after this optional chaining?
Analyze this Swift code using optional chaining. What is the value of 'result' after execution?
iOS Swift
class Person {
  var pet: Pet?
}
class Pet {
  var name: String
  init(name: String) { self.name = name }
}

let person = Person()
let result = person.pet?.name ?? "No pet"
AEmpty string ""
Bnil
C"No pet"
DCompilation error
Attempts:
2 left
💡 Hint
Optional chaining returns nil if any link in the chain is nil, then the nil-coalescing operator provides a default.
lifecycle
advanced
2:00remaining
Which option correctly unwraps and uses an optional in SwiftUI view?
In SwiftUI, you have an optional string 'username: String?'. Which code snippet safely unwraps and displays it in a Text view?
Aif let name = username { Text(name) } else { Text("Guest") }
BText(String(describing: username))
CText(username!)
DText(username ?? "Guest")
Attempts:
2 left
💡 Hint
Use nil-coalescing operator to provide a default value in UI.
🔧 Debug
expert
2:00remaining
What error does this Swift code produce?
Examine this Swift code snippet. What error will it cause when compiled or run?
iOS Swift
var optionalInt: Int? = 5
let forcedInt: Int = optionalInt
print(forcedInt)
AType mismatch error: Cannot assign 'Int?' to 'Int'
BRuntime crash due to nil unwrapping
CPrints 5
DCompilation error: Missing '!' for force unwrap
Attempts:
2 left
💡 Hint
You cannot assign an optional directly to a non-optional variable without unwrapping.