---
title: Optional
framework: swift
role: symbol
role_heading: Enumeration
path: swift/optional
---

# Optional

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

## Declaration

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

## Overview

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(_:)](swift/optional/some(_:).md)
- [init(_:)](swift/optional/init(_:).md)

### Creating a Nil Value

- [Optional.none](swift/optional/none.md)
- [init(nilLiteral:)](swift/optional/init(nilliteral:).md)

### Transforming an Optional Value

- [map(_:)](swift/optional/map(_:).md)
- [flatMap(_:)](swift/optional/flatmap(_:).md)

### Coalescing Nil Values

- [??(_:_:)](swift/__(_:_:)-9xjze.md)
- [??(_:_:)](swift/__(_:_:)-1fjjj.md)

### Comparing Optional Values

- [~=(_:_:)](swift/optional/~=(_:_:).md)

### Encoding and Decoding

- [encode(to:)](swift/optional/encode(to:).md)
- [init(from:)](swift/optional/init(from:).md)

### Inspecting an Optional

- [hash(into:)](swift/optional/hash(into:).md)
- [unsafelyUnwrapped](swift/optional/unsafelyunwrapped.md)
- [debugDescription](swift/optional/debugdescription.md)
- [customMirror](swift/optional/custommirror.md)

### Publishing an Optional

- [publisher](swift/optional/publisher-swift.property.md)
- [Optional.Publisher](swift/optional/publisher-swift.struct.md)

### Deprecated

- [hashValue](swift/optional/hashvalue.md)

### Operators

- [!=(_:_:)](swift/optional/!=(_:_:)-6y4t6.md)
- [!=(_:_:)](swift/optional/!=(_:_:)-9e46a.md)
- [==(_:_:)](swift/optional/==(_:_:)-1j2c8.md)
- [==(_:_:)](swift/optional/==(_:_:)-2tyup.md)

### Instance Methods

- [take()](swift/optional/take().md)

### Type Aliases

- [Optional.PartiallyGenerated](swift/optional/partiallygenerated.md)
- [Optional.Specification](swift/optional/specification.md)
- [Optional.TableRowBody](swift/optional/tablerowbody.md)
- [Optional.TicksCollection](swift/optional/tickscollection.md)
- [Optional.UnwrappedType](swift/optional/unwrappedtype.md)
- [Optional.ValueType](swift/optional/valuetype.md)

### Type Properties

- [defaultResolverSpecification](swift/optional/defaultresolverspecification.md)

### Default Implementations

- [AtomicRepresentable Implementations](swift/optional/atomicrepresentable-implementations.md)
- [CustomDebugStringConvertible Implementations](swift/optional/customdebugstringconvertible-implementations.md)
- [CustomReflectable Implementations](swift/optional/customreflectable-implementations.md)
- [Decodable Implementations](swift/optional/decodable-implementations.md)
- [Encodable Implementations](swift/optional/encodable-implementations.md)
- [Equatable Implementations](swift/optional/equatable-implementations.md)
- [ExpressibleByNilLiteral Implementations](swift/optional/expressiblebynilliteral-implementations.md)
- [Hashable Implementations](swift/optional/hashable-implementations.md)
- [IntentValueConvertible Implementations](swift/optional/intentvalueconvertible-implementations.md)
- [IntentValueExpressing Implementations](swift/optional/intentvalueexpressing-implementations.md)

## Relationships

### Conforms To

- [AccessibilityRotorContent](swiftui/accessibilityrotorcontent.md)
- [AtomicRepresentable](synchronization/atomicrepresentable.md)
- [AttachmentContent](realitykit/attachmentcontent.md)
- [AttributedTextFormattingDefinition](swiftui/attributedtextformattingdefinition.md)
- [AxisContent](charts/axiscontent.md)
- [AxisMark](charts/axismark.md)
- [BitwiseCopyable](swift/bitwisecopyable.md)
- [Chart3DContent](charts/chart3dcontent.md)
- [ChartContent](charts/chartcontent.md)
- [Commands](swiftui/commands.md)
- [ConvertibleToGeneratedContent](foundationmodels/convertibletogeneratedcontent.md)
- [Copyable](swift/copyable.md)
- [CustomDebugStringConvertible](swift/customdebugstringconvertible.md)
- [CustomReflectable](swift/customreflectable.md)
- [CustomTestStringConvertible](testing/customteststringconvertible.md)
- [CustomizableToolbarContent](swiftui/customizabletoolbarcontent.md)
- [Decodable](swift/decodable.md)
- [DecodableWithConfiguration](foundation/decodablewithconfiguration.md)
- [DynamicInstructions](foundationmodels/dynamicinstructions.md)
- [Encodable](swift/encodable.md)
- [EncodableWithConfiguration](foundation/encodablewithconfiguration.md)
- [Equatable](swift/equatable.md)
- [Escapable](swift/escapable.md)
- [ExpressibleByNilLiteral](swift/expressiblebynilliteral.md)
- [Gesture](swiftui/gesture.md)
- [Hashable](swift/hashable.md)
- [InstructionsRepresentable](foundationmodels/instructionsrepresentable.md)
- [IntentValueConvertible](appintents/intentvalueconvertible.md)
- [IntentValueExpressing](appintents/intentvalueexpressing.md)
- [MapContent](mapkit/mapcontent.md)
- [PromptRepresentable](foundationmodels/promptrepresentable.md)
- [RelationshipCollection](swiftdata/relationshipcollection.md)
- [SceneAccessoryContent](swiftui/sceneaccessorycontent.md)
- [Sendable](swift/sendable.md)
- [SendableMetatype](swift/sendablemetatype.md)
- [SliderTickContent](swiftui/slidertickcontent.md)
- [StoreContent](storekit/storecontent.md)
- [TabContent](swiftui/tabcontent.md)
- [TableColumnContent](swiftui/tablecolumncontent.md)
- [TableRowContent](swiftui/tablerowcontent.md)
- [ToolbarContent](swiftui/toolbarcontent.md)
- [View](swiftui/view.md)
