You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Optionals are one of Swift's most important safety features. An optional represents a value that might be absent. This lesson covers optional types, unwrapping techniques, and best practices.
An optional is a type that can hold either a value or nil (no value):
var name: String? = "Alice" // has a value
var age: Int? = nil // no value
// Without the ?, the type cannot be nil
// var greeting: String = nil // Error: 'nil' cannot be assigned to type 'String'
Under the hood, Optional<T> is an enum:
enum Optional<Wrapped> {
case none // nil
case some(Wrapped) // a value
}
In many languages, any reference can be null, leading to runtime crashes. Swift makes the possibility of absence explicit in the type system:
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.