Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Swift Optional (Optionals) Types

Swift Optional (Optionals) Types

Optional types are used to represent "there may be a value here, or there may not".

When a variable may be "empty", declare it as an optional; Swift forces you to handle that "empty" case before use, eliminating many null-pointer problems at compile time.

This article is based on Swift 6.x, and the examples can be run directly with the swift command.


Optional and T?

An optional type is essentially a generic enum Optional, which has only two values: .some(value) and .none.

Optional types expand to the Optional generic enum: String? is an Optional, which has only two cases, .some(String) and .none; optional chaining only continues on .some, the nil-coalescing operator supplies a default value on .none, and forced unwrapping traps when it encounters .none

Swift provides the postfix question mark T? as shorthand for Optional , and the two are completely equivalent.

Example

import Foundation

// All three forms are completely equivalent

var a

:

Int

?

=

42

var b

:

Optional

<

Int

=

42

var c

:

Int

?

=

nil

print

(

a as Any

)

print

(

b as Any

)

print

(

c as Any

)

// An optional type is essentially an enum: .some(value) or .none

let someValue

:

Int

?

=

.

some

(

7

)

let noneValue

:

Int

?

=

.

none

print

(

someValue as Any, noneValue as Any

)

// Declare an optional variable without assigning it; it defaults to nil

var site

:

String

?

print

(

site as Any

)

site

=

"www.runoob.com"

print

(

site as Any

)

// Optional array: the ? applies to the entire [Int], not to Int

var numbers

:

[

Int

]

?

=

[

1

,

2

,

3

]

print

(

numbers as Any

)

numbers

=

nil

print

(

numbers as Any

)

Running result:



Optional(42)

Optional(42)

nil

Optional(7) nil

nil

Optional("www.runoob.com")

Optional([1, 2, 3])

nil

From the output you can see that optional values print with Optional(...) around them, while nil prints as nil.

Note:When declaring an optional array, the question mark applies to the whole array type, written as [Int]?; don't use the old syntax with square brackets after the type name, which Swift removed long ago.


nil is not a Boolean value

This is the habit beginners most easily bring over from other languages: using an optional directly as a condition.

In Swift, the condition of if and while must be a real Bool; optionals cannot be automatically converted to Bool.

Example

var site

:

String

?

=

"www.runoob.com"

if

site

{

    print

(

site

)

}

Compile error:



error: optional type 'String?' cannot be used as a boolean;

test for '!= nil' instead

The correct approach is to explicitly check for nil, or use optional binding described later.

Example

var site

:

String

?

=

"www.runoob.com"

// Explicit check

if

site

!

=

nil

{

    print

(

"Has value"

)

}

else

{

    print

(

"No value"

)

}

Running result:



有值

Likewise, nil is not a Boolean literal; Bool only has the values true and false.

Example

var flag

:

Bool

=

nil

Compile error:



error: 'nil' cannot initialize specified type 'Bool'

note: add '?' to form the optional type 'Bool?'

If you truly need a Boolean state for "no value", declare it as Bool? and use optional binding to extract the real Boolean.


Forced unwrapping

Add an exclamation mark ! after an optional value to mean "I'm certain there's a value here, take it out directly".

The result of forced unwrapping is no longer an optional and can be used directly in computations.

Example

import Foundation

var site

:

String

?

=

"www.runoob.com"

// Forced unwrapping: use when you're sure there's a value

print

(

site

!

)

// A safer approach: check first, then unwrap

if

site

!

=

nil

{

    print

(

"The site is (site!)"

)

}

Running result:



www.runoob.com

网站是 www.runoob.com

But if the optional is actually nil, forced unwrapping will crash the program.

Example

var site

:

String

?

=

nil

print

(

site

!

)

Running result:



Fatal error: Unexpectedly found nil while unwrapping an Optional value

Note:Forced unwrapping is a runtime check, not a compile-time check. Unless you're 100% sure there's a value, use optional binding or the nil-coalescing operator.


Optional binding: if let and guard let

Optional binding binds the unwrapped value to a new constant and only executes the branch when there really is a value, completely avoiding the risk of a crash.

An if let scope is limited to inside the branch; guard let is for early exit, with the unwrapped value available in all subsequent code.

Example

import Foundation

var site

:

String

?

=

"www.runoob.com"

// Optional binding: bind the unwrapped value to a new constant

if

let url

=

site

{

    print

(

"Optional binding gives: (url)"

)

}

// guard let: exit early when the condition isn't met; the unwrapped value stays available afterward

func runoobPrint

(

_ value

:

String

?

)

{

    guard let text

=

value

else

{

        print

(

"Value is nil, returning early"

)

       

return

   

}

    print

(

"guard let unwrapped successfully: (text), length (text.count)"

)

}

runoobPrint

(

"RUNOOB"

)

runoobPrint

(

nil

)

Running result:



可选绑定得到:www.runoob.com

guard let 解包成功:RUNOOB,长度 6

值为 nil,直接返回

In real coding, for "exit if not satisfied" scenarios like function parameter validation, dictionary lookup, and type conversion, prefer guard let to reduce nesting.


Shorthand binding if let x

If the bound constant has the same name as the optional variable, Swift lets you omit = variableName and just write if let x {

This shorthand also applies to guard let, making code shorter and avoiding repeated variable names.

Example

import Foundation

var site

:

String

?

=

"www.runoob.com"

var tag

:

Int

?

=

2026

// Shorthand binding: when the variable name matches the optional, you can omit the right side of =

if

let site

{

    print

(

"Shorthand binding: (site)"

)

}

// Shorthand binding also applies to guard let

func runoobCheck

(

_ value

:

Int

?

)

{

    guard let value

else

{

        print

(

"No value"

)

       

return

   

}

    print

(

"guard shorthand binding: (value)"

)

}

runoobCheck

(

100

)

runoobCheck

(

nil

)

// Bind multiple optionals at once; the branch runs only if all have values

if

let site, let tag

{

    print

(

"Both have values: (site) - (tag)"

)

}

else

{

    print

(

"At least one is nil"

)

}

tag

=

nil

if

let site, let tag

{

    print

(

"Both have values: (site) - (tag)"

)

}

else

{

    print

(

"At least one is nil, condition not satisfied"

)

}

Running result:



简写绑定:www.runoob.com

guard 简写绑定:100

没有值

两个都有值:www.runoob.com - 2026

至少有一个为 nil,条件不成立

When multiple optionals are joined by commas, all must have values to enter the branch, equivalent to consecutive &&.


The nil-coalescing operator ??

?? provides a default value for an optional: if the left side has a value, take it; if it's nil, take the right side.

It's more compact than if let, suitable for "use it if present, otherwise use a default" scenarios.

Example

import Foundation

var site

:

String

?

=

nil

// ?? provides a default: use the left side if it has a value, otherwise use the right side

let name

=

site

??

"www.runoob.com"

print

(

name

)

site

=

"RUNOOB"

print

(

site

??

"Default value"

)

// ?? can be chained

var a

:

Int

?

=

nil

var b

:

Int

?

=

nil

print

(

a

??

b

??

0

)

Running result:



www.runoob.com

RUNOOB

0

Note that the type on the right of ?? must match the unwrapped type on the left, otherwise the compiler reports a type mismatch.


Implicitly unwrapped optionals T!

An optional declared with an exclamation mark after the type is called an Implicitly Unwrapped Optional; you don't need to write ! when using it.

Example

import Foundation

// Implicitly unwrapped optional T!: automatically unwrapped after declaration, no need to write !

struct

RunoobUser

{

    var name

:

String

!

}

let user

=

RunoobUser

(

name

:

"Runoob Tutorial"

)

// Here user.name is automatically unwrapped into a String

print

(

user.

name

.

count

)

Running result:



4

An implicitly unwrapped optional is still an optional at heart; it's just force-unwrapped on every access, so it still crashes if it's nil.

Note:Implicitly unwrapped optionals are no longer recommended. They only suit the rare case where a value is definitely assigned after creation and never becomes nil again; modern Swift code should prefer ordinary optionals with optional binding.


Common questions

Finally, let's address a few frequently asked questions.

Why does printing an optional add "Optional"

Because you're printing the optional itself rather than the value inside. To print clean content, unwrap first, e.g. print(site ?? "") or use if let before printing.

Can optionals be compared?

Yes. When the underlying type supports ==, optionals can be compared with each other and with nil, e.g. site == nil, a == b.

How to write multiple unwrappings more concisely

Use shorthand binding with commas, e.g. if let a, let b, let c { ... }; you can also append extra conditions directly, as in if let a, a > 0 { ... }.

What's the difference between optional chaining and optional binding?

Optional binding is "take it out and use it", while optional chaining is "access along the optional all the way; if any step is nil, the whole thing returns nil"; for details see "Swift Optional Chaining》。