<!--
{
  "availability" : [
    "iOS: 8.0.0 -",
    "iPadOS: 8.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.10.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Swift",
  "identifier" : "/documentation/Swift/Optional",
  "metadataVersion" : "0.1.0",
  "role" : "Enumeration",
  "symbol" : {
    "kind" : "Enumeration",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:Sq"
  },
  "title" : "Optional"
}
-->

# Optional

A type that represents either a wrapped value or the absence of a value.

```
@frozen enum Optional<Wrapped> where Wrapped : ~Copyable, Wrapped : ~Escapable
```

## Overview

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.

## Topics

### Creating an Optional Value

[`Optional.some(_:)`](/documentation/Swift/Optional/some(_:))

The presence of a value, stored as `Wrapped`.

[`init(_:)`](/documentation/Swift/Optional/init(_:))

Creates an instance that stores the given value.

### Creating a Nil Value

[`Optional.none`](/documentation/Swift/Optional/none)

The absence of a value.

[`init(nilLiteral:)`](/documentation/Swift/Optional/init(nilLiteral:))

Creates an instance initialized with `nil`.

### Transforming an Optional Value

[`map(_:)`](/documentation/Swift/Optional/map(_:))

Evaluates the given closure when this `Optional` instance is not `nil`,
passing the unwrapped value as a parameter.

[`flatMap(_:)`](/documentation/Swift/Optional/flatMap(_:))

Evaluates the given closure when this `Optional` instance is not `nil`,
passing the unwrapped value as a parameter.

### Coalescing Nil Values

[`??(_:_:)`](/documentation/Swift/__(_:_:)-9xjze)

Performs a nil-coalescing operation, returning the wrapped value of an
`Optional` instance or a default value.

[`??(_:_:)`](/documentation/Swift/__(_:_:)-1fjjj)

Performs a nil-coalescing operation, returning the wrapped value of an
`Optional` instance or a default `Optional` value.

### Comparing Optional Values

[`~=(_:_:)`](/documentation/Swift/Optional/~=(_:_:))

Returns a Boolean value indicating whether an argument matches `nil`.

### Encoding and Decoding

[`encode(to:)`](/documentation/Swift/Optional/encode(to:))

Encodes this optional value into the given encoder.

[`init(from:)`](/documentation/Swift/Optional/init(from:))

Creates a new instance by decoding from the given decoder.

### Inspecting an Optional

[`hash(into:)`](/documentation/Swift/Optional/hash(into:))

Hashes the essential components of this value by feeding them into the
given hasher.

[`unsafelyUnwrapped`](/documentation/Swift/Optional/unsafelyUnwrapped)

The wrapped value of this instance, unwrapped without checking whether
the instance is `nil`.

[`debugDescription`](/documentation/Swift/Optional/debugDescription)

A textual representation of this instance, suitable for debugging.

[`customMirror`](/documentation/Swift/Optional/customMirror)

The custom mirror for this instance.

### Publishing an Optional

[`publisher`](/documentation/Swift/Optional/publisher-swift.property)

A Combine publisher that publishes this instance’s value to each subscriber exactly once, if it has any value at all.

[`Publisher`](/documentation/Swift/Optional/Publisher-swift.struct)

The type of a Combine publisher that publishes the value of a Swift optional instance to each subscriber exactly once, if the instance has any value at all.

### Deprecated

[`hashValue`](/documentation/Swift/Optional/hashValue)

The hash value.

## Relationships

### Conforms To

[`ToolbarContent`](/documentation/SwiftUI/ToolbarContent)

[`Encodable`](/documentation/Swift/Encodable)

[`SliderTickContent`](/documentation/SwiftUI/SliderTickContent)

[`Commands`](/documentation/SwiftUI/Commands)

[`BitwiseCopyable`](/documentation/Swift/BitwiseCopyable)

[`Gesture`](/documentation/SwiftUI/Gesture)

[`AxisContent`](/documentation/Charts/AxisContent)

[`AtomicRepresentable`](/documentation/Synchronization/AtomicRepresentable)

[`TableColumnContent`](/documentation/SwiftUI/TableColumnContent)

[`Escapable`](/documentation/Swift/Escapable)

[`MapContent`](/documentation/MapKit/MapContent)

[`IntentValueConvertible`](/documentation/AppIntents/IntentValueConvertible)

[`Sendable`](/documentation/Swift/Sendable)

[`IntentValueExpressing`](/documentation/AppIntents/IntentValueExpressing)

[`SendableMetatype`](/documentation/Swift/SendableMetatype)

[`CustomDebugStringConvertible`](/documentation/Swift/CustomDebugStringConvertible)

[`CustomReflectable`](/documentation/Swift/CustomReflectable)

[`DecodableWithConfiguration`](/documentation/Foundation/DecodableWithConfiguration)

[`AttributedTextFormattingDefinition`](/documentation/SwiftUI/AttributedTextFormattingDefinition)

[`RelationshipCollection`](/documentation/SwiftData/RelationshipCollection)

[`AttachmentContent`](/documentation/RealityKit/AttachmentContent)

[`InstructionsRepresentable`](/documentation/FoundationModels/InstructionsRepresentable)

[`ChartContent`](/documentation/Charts/ChartContent)

[`CustomTestStringConvertible`](/documentation/Testing/CustomTestStringConvertible)

[`ExpressibleByNilLiteral`](/documentation/Swift/ExpressibleByNilLiteral)

[`PromptRepresentable`](/documentation/FoundationModels/PromptRepresentable)

[`EncodableWithConfiguration`](/documentation/Foundation/EncodableWithConfiguration)

[`ConvertibleToGeneratedContent`](/documentation/FoundationModels/ConvertibleToGeneratedContent)

[`AxisMark`](/documentation/Charts/AxisMark)

[`Copyable`](/documentation/Swift/Copyable)

[`Equatable`](/documentation/Swift/Equatable)

[`Decodable`](/documentation/Swift/Decodable)

[`AccessibilityRotorContent`](/documentation/SwiftUI/AccessibilityRotorContent)

[`CustomizableToolbarContent`](/documentation/SwiftUI/CustomizableToolbarContent)

[`TableRowContent`](/documentation/SwiftUI/TableRowContent)

[`DynamicInstructions`](/documentation/FoundationModels/DynamicInstructions)

[`View`](/documentation/SwiftUI/View)

[`Chart3DContent`](/documentation/Charts/Chart3DContent)

[`SceneAccessoryContent`](/documentation/SwiftUI/SceneAccessoryContent)

[`Hashable`](/documentation/Swift/Hashable)

[`StoreContent`](/documentation/StoreKit/StoreContent)

[`TabContent`](/documentation/SwiftUI/TabContent)

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)