Enumerationswift 6.0.1Swift
Optional
A type that represents either a wrapped value or the absence of a value.
@frozen enum Optional<Wrapped> where Wrapped : ~Copyable
You 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 shortForm
and longForm
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.none
is equivalent to the nil
literal. Optional.some(Wrapped)
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 imagePaths["star"]
has type Optional<String>
or, written in the preferred manner, String?
.
Optional Binding
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'"
Optional Chaining
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 hasSuffix(_:)
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"
Using the Nil-Coalescing Operator
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 imagePaths
.
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"
Unconditional Unwrapping
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.
Cases
case none
The absence of a value.
case some(Wrapped)
The presence of a value, stored as
Wrapped
.
Citizens in Swift
Type members
init(consuming Wrapped
) Creates an instance that stores the given value.
init(nilLiteral: ()
) Creates an instance initialized with
nil
.static func != (lhs: _OptionalNilComparisonType, rhs: borrowing Wrapped?
) -> Bool Returns a Boolean value indicating whether the right-hand-side argument is not
nil
.static func != (lhs: borrowing Wrapped?, rhs: _OptionalNilComparisonType
) -> Bool Returns a Boolean value indicating whether the left-hand-side argument is not
nil
.static func == (lhs: _OptionalNilComparisonType, rhs: borrowing Wrapped?
) -> Bool Returns a Boolean value indicating whether the right-hand-side argument is
nil
.static func == (lhs: borrowing Wrapped?, rhs: _OptionalNilComparisonType
) -> Bool Returns a Boolean value indicating whether the left-hand-side argument is
nil
.static func ~= (lhs: _OptionalNilComparisonType, rhs: borrowing Wrapped?
) -> Bool Returns a Boolean value indicating whether an argument matches
nil
.
Instance members
var customMirror: Mirror
var debugDescription: String
A textual representation of this instance, suitable for debugging.
var unsafelyUnwrapped: Wrapped
The wrapped value of this instance, unwrapped without checking whether the instance is
nil
.func flatMap<E, U>((Wrapped)
throws Evaluates the given closure when this
Optional
instance is notnil
, passing the unwrapped value as a parameter.func map<E, U>((Wrapped)
throws Evaluates the given closure when this
Optional
instance is notnil
, passing the unwrapped value as a parameter.func take(
) -> Optional<Wrapped> Takes the wrapped value being stored in this instance and returns it while also setting the instance to
nil
. If there is no value being stored in this instance, this returnsnil
instead.
Citizens in Swift
where Wrapped:Encodable
Conformances
protocol Encodable
A type that can encode itself to an external representation.
Instance members
func encode(to: any Encoder
) throws Encodes this optional value into the given encoder.
Citizens in Swift
where Wrapped:Hashable
Conformances
protocol Hashable
A type that can be hashed into a
Hasher
to produce an integer hash value.
Instance members
func hash(into: inout Hasher
) Hashes the essential components of this value by feeding them into the given hasher.
Citizens in Swift
where Wrapped:Equatable
Conformances
protocol Equatable
A type that can be compared for value equality.
Type members
static func == (lhs: Wrapped?, rhs: Wrapped?
) -> Bool Returns a Boolean value indicating whether two optional instances are equal.
Type features
static func != (lhs: Self, rhs: Self
) -> Bool Returns a Boolean value indicating whether two values are not equal.
Citizens in Swift
where Wrapped:Decodable
Conformances
protocol Decodable
A type that can decode itself from an external representation.
Type members
Citizens in Swift
where Wrapped:BitwiseCopyable
Conformances
Citizens in Swift
Conformances
protocol CustomDebugStringConvertible
A type with a customized textual representation suitable for debugging purposes.
protocol CustomReflectable
A type that explicitly supplies its own mirror.
Citizens in Swift
Conformances
Citizens in Swift
where Wrapped:Escapable
Conformances
protocol ExpressibleByNilLiteral
A type that can be initialized using the nil literal,
nil
.
Available in _Differentiation
where Wrapped:Differentiable
Conformances
protocol Copyable
A type whose values can be implicitly or explicitly copied.
protocol Differentiable
A type that mathematically represents a differentiable manifold whose tangent spaces are finite-dimensional.
protocol Escapable
Types
Instance members
Available in Synchronization
where Wrapped:AtomicOptionalRepresentable
Conformances
protocol AtomicRepresentable
A type that supports atomic operations through a separate atomic storage representation.
protocol Copyable
A type whose values can be implicitly or explicitly copied.
protocol Escapable
Typealiases
Type members
Available in Cxx
Type members
Available in Cxx
where Wrapped:UnsafeCxxInputIterator
Conformances
protocol Copyable
A type whose values can be implicitly or explicitly copied.
protocol Escapable
protocol UnsafeCxxInputIterator
Bridged C++ iterator that allows to traverse the elements of a sequence using a for-in loop.
Typealiases
Instance members
Available in FoundationEssentials
where Wrapped:DecodableWithConfiguration
Conformances
Type members
Available in FoundationEssentials
where Wrapped:EncodableWithConfiguration
Conformances
Instance members
Extension in NIOCore
Instance members
func setOrCascade<Value>(to: EventLoopPromise<Value>?
) Sets or cascades the future result of self to the provided promise, if present.
Extension in NIOCore
where Wrapped == ByteBuffer
Instance members
func setOrWriteBuffer(inout ByteBuffer
) -> Int If
nil
, replaceself
with.some(buffer)
. If non-nil
, writebuffer
’s readable bytes into theByteBuffer
starting atwriterIndex
.func setOrWriteImmutableBuffer(ByteBuffer
) -> Int If
nil
, replaceself
with.some(buffer)
. If non-nil
, writebuffer
’s readable bytes into theByteBuffer
starting atwriterIndex
.
Extension in Testing
Instance members
Extension in Testing
Conformances
protocol CustomTestStringConvertible
A protocol describing types with a custom string representation when presented as part of a test’s output.
Extension in Vapor
Conformances
protocol AnyOptionalType
Type-erased
OptionalType
protocol OptionalType
Capable of being represented by an optional wrapped type.
Typealiases
typealias WrappedType
See
OptionalType.WrappedType
Type members
static func makeOptionalType(Wrapped?
) -> Optional<Wrapped> See
OptionalType.makeOptionalType
Instance members
var wrapped: Wrapped?
See
OptionalType.wrapped
Type features
static var anyWrappedType: Any.Type
See
AnyOptionalType.anyWrappedType
Instance features
var anyWrapped: Any?
See
AnyOptionalType.anyWrapped
Extension in Vapor
where Wrapped == StackTrace