SwiftMidMCQ
What is `Optional` and how does it work?
Test your knowledge:
Explanation & Code
Answer:
An Optional is a type that can hold either a value or nil. It's Swift's way of expressing the absence of a value safely, avoiding null pointer crashes common in Objective-C.
Code Example:
var name: String? = "Alice" // Optional String
var age: Int? = nil // no value
// Unwrapping safely
if let name = name {
print("Hello, \(name)")
}
// Nil coalescing — provide a default
let displayName = name ?? "Guest"
// Optional chaining — safely access properties
let count = name?.count // returns Int? not Int
Key Points:
String?is shorthand forOptional<String>- Never force unwrap (
!) unless you are 100% certain it has a value - Prefer
if let,guard let, or??for safe unwrapping
Rate your understanding: