Browse Questions
- A retain cycle occurs when two objects hold strong references to each other, preventing ARC from deallocating either.
- Combine subscriptions and NotificationCenter block observers cause leaks when the observation token is stored on self while the callback closure captures self strongly.
- Clean Architecture organises code into concentric layers where dependencies only point inward.
- An Optional is a type that can hold either a value or nil.
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