Optional / ? / !
Swift's Optional is a type that represents "a value that may or may not exist." Declare an Optional by appending ? to the type name, enabling nil-safe programming.
Syntax
// Declaring an Optional type var variableName: Type? = value var variableName: Type? = nil // Force unwrapping (only when you are certain the value is not nil) variableName! // Optional.none and Optional.some Optional<Type>.none // same as nil Optional<Type>.some(value) // an Optional wrapping a value
Syntax Reference
| Syntax | Description |
|---|---|
| Type? | Declares an Optional type. Can hold a value or nil. |
| nil | A special value representing the absence of a value. |
| variable! | Force-unwraps the Optional. Crashes at runtime if the value is nil. |
| variable == nil | Checks whether the value is nil. |
| variable != nil | Checks whether a value exists. |
| Optional.some(value) | Wraps a value in an Optional (explicit syntax). |
| Optional.none | The Optional representation equivalent to nil. |
Sample Code
// Declaring Optional types
var name: String? = "Taro"
var age: Int? = nil
print(name) // Optional("Taro")
print(age) // nil
// nil check
if name != nil {
print("Name exists: \(name!)") // Force unwrap (nil already confirmed)
}
// Updating Optionals
name = nil // can assign nil
age = 25 // can assign a value
print(name) // nil
print(age) // Optional(25)
// Explicit use of Optional.some and Optional.none
let value: Optional<Int> = Optional.some(42)
let empty: Optional<Int> = Optional.none
print(value) // Optional(42)
print(empty) // nil
// Converting a String Optional to Int (standard library example)
let str = "123"
let parsed = Int(str) // return type is Int? (nil if conversion fails)
print(parsed) // Optional(123)
let invalid = "abc"
let failed = Int(invalid)
print(failed) // nil
Overview
Optional is at the core of Swift's type system. In languages where null pointer dereference errors can occur silently, Swift's compiler enforces safe unwrapping to prevent crashes.
Force unwrapping (!) crashes at runtime if the value is nil, so use it with care. Force-unwrapping a nil value causes a runtime error (EXC_BAD_INSTRUCTION). Use if let, guard let, or the ?? operator for safe unwrapping.
For safe Optional unwrapping, see if let / guard let (Optional Binding).
If you find any errors or copyright issues, please contact us.