casesome(Wrapped) Wrapped.init(consumingWrapped) @frozen
enum Optional<Wrapped> where Wrapped : ~CopyableYou use the Optional type whenever you use optional values, even if you never type the word Optional. Swift’s type system usually shows the wrapped type’s name with a trailing question mark (?) instead of showing the full type name. For example, if a variable has the type Int?, that’s just another way of writing Optional<Int>. The shortened form is preferred for ease of reading and writing code.
The types of short and long in the following code sample are the same:
let shortForm: Int? = Int("42")
let longForm: Optional<Int> = Int("42")
The Optional type is an enumeration with two cases. Optional is equivalent to the nil literal. Optional stores a wrapped value. For example:
let number: Int? = Optional.some(42)
let noNumber: Int? = Optional.none
print(noNumber == nil)
// Prints "true"
You must unwrap the value of an Optional instance before you can use it in many contexts. Because Swift provides several ways to safely unwrap optional values, you can choose the one that helps you write clear, concise code.
The following examples use this dictionary of image names and file paths:
let imagePaths = ["star": "/glyphs/star.png",
"portrait": "/images/content/portrait.jpg",
"spacer": "/images/shared/spacer.gif"]
Getting a dictionary’s value using a key returns an optional value, so image has type Optional<String> or, written in the preferred manner, String?.
To conditionally bind the wrapped value of an Optional instance to a new variable, use one of the optional binding control structures, including if let, guard let, and switch.
if let starPath = imagePaths["star"] {
print("The star image is at '\(starPath)'")
} else {
print("Couldn't find the star image")
}
// Prints "The star image is at '/glyphs/star.png'"
To safely access the properties and methods of a wrapped instance, use the postfix optional chaining operator (postfix ?). The following example uses optional chaining to access the has method on a String? instance.
if imagePaths["star"]?.hasSuffix(".png") == true {
print("The star image is in PNG format")
}
// Prints "The star image is in PNG format"
Use the nil-coalescing operator (??) to supply a default value in case the Optional instance is nil. Here a default path is supplied for an image that is missing from image.
let defaultImagePath = "/images/default.png"
let heartPath = imagePaths["heart"] ?? defaultImagePath
print(heartPath)
// Prints "/images/default.png"
The ?? operator also works with another Optional instance on the right-hand side. As a result, you can chain multiple ?? operators together.
let shapePath = imagePaths["cir"] ?? imagePaths["squ"] ?? defaultImagePath
print(shapePath)
// Prints "/images/default.png"
When you’re certain that an instance of Optional contains a value, you can unconditionally unwrap the value by using the forced unwrap operator (postfix !). For example, the result of the failable Int initializer is unconditionally unwrapped in the example below.
let number = Int("42")!
print(number)
// Prints "42"
You can also perform unconditional optional chaining by using the postfix ! operator.
let isPNG = imagePaths["star"]!.hasSuffix(".png")
print(isPNG)
// Prints "true"
Unconditionally unwrapping a nil instance with ! triggers a runtime error.
casesome(Wrapped) Wrapped.init(consumingWrapped) casenone init(nilLiteral : ()) nil.funcflatMap <E, U>((Wrapped) throws(E) -> U?) throws(E) -> U? Optional instance is not nil, passing the unwrapped value as a parameter.func??<T>(consumingT?, @autoclosure () throws-> T) rethrows-> T Optional instance or a default value.func??<T>(consumingT?, @autoclosure () throws-> T?) rethrows-> T? Optional instance or a default Optional value.staticfunc~=(_OptionalNilComparisonType , borrowingWrapped?) -> Bool nil.funcencode(to: any Encoder) throws init(from: any Decoder) throws funchash(into: inoutHasher) varunsafelyUnwrapped : Wrapped nil.vardebugDescription : String varcustomMirror : Mirror varpublisher: Optional<Wrapped>.Publisher structPublisher varhashValue : Int staticfunc!=(borrowingWrapped?, _OptionalNilComparisonType ) -> Bool nil.staticfunc!=(_OptionalNilComparisonType , borrowingWrapped?) -> Bool nil.staticfunc==(borrowingWrapped?, _OptionalNilComparisonType ) -> Bool nil.staticfunc==(_OptionalNilComparisonType , borrowingWrapped?) -> Bool nil.funcmap<E, U>((Wrapped) throws(E) -> U) throws(E) -> U? Optional instance is not nil, passing the unwrapped value as a parameter.AtomicRepresentable Wrapped conforms to AtomicOptionalRepresentable .AttachmentContent AxisContent AxisMark BitwiseCopyable Wrapped conforms to BitwiseCopyable .ChartContent CommandsCopyableWrapped conforms to BitwiseCopyable .CustomDebugStringConvertible Wrapped conforms to Copyable and Escapable.CustomReflectable Wrapped conforms to Copyable and Escapable.CustomTestStringConvertible CustomizableToolbarContent DecodableWrapped conforms to Decodable.DecodableWithConfiguration EncodableWrapped conforms to Encodable.EncodableWithConfiguration EquatableWrapped conforms to Hashable.ExpressibleByNilLiteral Wrapped conforms to Escapable.GestureHashableWrapped conforms to Hashable.MapContent RelationshipCollection SendableWrapped conforms to Escapable and Sendable.StoreContent TabContent TableColumnContent TableRowContent ToolbarContent View