enum Optional<Wrapped>
Inheritance |
CustomDebugStringConvertible, CustomReflectable, Decodable, Encodable, Equatable, ExpressibleByNilLiteral, Hashable
View Protocol Hierarchy →
|
---|---|
Import | import Swift |
Cases
The absence of a value.
In code, the absence of a value is typically written using the nil
literal rather than the explicit .none
enumeration case.
Declaration
Initializers
Creates a new instance by decoding from the given decoder.
This initializer throws an error if reading from the decoder fails, or if the data read is corrupted or otherwise invalid.
decoder
: The decoder to read data from.
Declaration
init(from decoder: Decoder)
Creates an instance initialized with nil
.
Do not call this initializer directly. It is used by the compiler when you
initialize an Optional
instance with a nil
literal. For example:
var i: Index? = nil
In this example, the assignment to the i
variable calls this
initializer behind the scenes.
Declaration
init(nilLiteral: ())
Instance Variables
The custom mirror for this instance.
If this type has value semantics, the mirror should be unaffected by subsequent mutations of the instance.
Declaration
var customMirror: Mirror { get }
A textual representation of this instance, suitable for debugging.
Declaration
var debugDescription: String { get }
The hash value for the optional instance.
Two optionals that are equal will always have equal hash values.
Hash values are not guaranteed to be equal across different executions of your program. Do not save hash values to use during a future execution.
Declaration
var hashValue: Int { get }
The wrapped value of this instance, unwrapped without checking whether
the instance is nil
.
The unsafelyUnwrapped
property provides the same value as the forced
unwrap operator (postfix !
). However, in optimized builds (-O
), no
check is performed to ensure that the current instance actually has a
value. Accessing this property in the case of a nil
value is a serious
programming error and could lead to undefined behavior or a runtime
error.
In debug builds (-Onone
), the unsafelyUnwrapped
property has the same
behavior as using the postfix !
operator and triggers a runtime error
if the instance is nil
.
The unsafelyUnwrapped
property is recommended over calling the
unsafeBitCast(_:)
function because the property is more restrictive
and because accessing the property still performs checking in debug
builds.
Warning: This property trades safety for performance. Use
unsafelyUnwrapped
only when you are confident that this instance
will never be equal to nil
and only after you've tried using the
postfix !
operator.
Declaration
var unsafelyUnwrapped: Wrapped { get }
Instance Methods
Encodes this optional value into the given encoder.
This function throws an error if any values are invalid for the given encoder's format.
encoder
: The encoder to write data to.
Declaration
func encode(to encoder: Encoder) throws
Evaluates the given closure when this Optional
instance is not nil
,
passing the unwrapped value as a parameter.
Use the flatMap
method with a closure that returns an optional value.
This example performs an arithmetic operation with an optional result on
an optional integer.
let possibleNumber: Int? = Int("42")
let nonOverflowingSquare = possibleNumber.flatMap { x -> Int? in
let (result, overflowed) = x.multipliedReportingOverflow(by: x)
return overflowed ? nil : result
}
print(nonOverflowingSquare)
// Prints "Optional(1764)"
transform
: A closure that takes the unwrapped value
of the instance.
Returns: The result of the given closure. If this instance is nil
,
returns nil
.
Declaration
func flatMap<U>(_ transform: (Wrapped) throws -> U?) rethrows -> U?
Hashes the essential components of this value by feeding them into the given hasher.
hasher
: The hasher to use when combining the components
of this instance.
Declaration
func hash(into hasher: inout Hasher)
Evaluates the given closure when this Optional
instance is not nil
,
passing the unwrapped value as a parameter.
Use the map
method with a closure that returns a nonoptional value.
This example performs an arithmetic operation on an
optional integer.
let possibleNumber: Int? = Int("42")
let possibleSquare = possibleNumber.map { $0 * $0 }
print(possibleSquare)
// Prints "Optional(1764)"
let noNumber: Int? = nil
let noSquare = noNumber.map { $0 * $0 }
print(noSquare)
// Prints "nil"
transform
: A closure that takes the unwrapped value
of the instance.
Returns: The result of the given closure. If this instance is nil
,
returns nil
.
Declaration
func map<U>(_ transform: (Wrapped) throws -> U) rethrows -> U?
A type that represents either a wrapped value or
nil
, the absence of a value.You use the
Optional
type whenever you use optional values, even if you never type the wordOptional
. 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 typeInt?
, that's just another way of writingOptional<Int>
. The shortened form is preferred for ease of reading and writing code.The types of
shortForm
andlongForm
in the following code sample are the same:The
Optional
type is an enumeration with two cases.Optional.none
is equivalent to thenil
literal.Optional.some(Wrapped)
stores a wrapped value. For example: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:
Getting a dictionary's value using a key returns an optional value, so
imagePaths["star"]
has typeOptional<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, includingif let
,guard let
, andswitch
.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 thehasSuffix(_:)
method on aString?
instance.Using the Nil-Coalescing Operator
Use the nil-coalescing operator (
??
) to supply a default value in case theOptional
instance isnil
. Here a default path is supplied for an image that is missing fromimagePaths
.The
??
operator also works with anotherOptional
instance on the right-hand side. As a result, you can chain multiple??
operators together.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 failableInt
initializer is unconditionally unwrapped in the example below.You can also perform unconditional optional chaining by using the postfix
!
operator.Unconditionally unwrapping a
nil
instance with!
triggers a runtime error.