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

Swift Optional Chaining

Swift Optional Chaining

Optional chaining is a way to safely access properties, methods, or subscripts on a value that may be nil.

It compresses "first check whether it's nil, then get the value" into a single question mark: if any link in the chain is nil, the whole expression returns nil and the program doesn't crash.


Optional chaining syntax

Put a question mark ? right after the optional value, then write the property, method, or subscript as usual—that's optional chaining.

First, let's define a set of model classes used throughout this article; they form a chain Person → Residence → Address → Room.

Example

import Foundation

// Room

class

Room

{

    let name

:

String

    init

(

name

:

String

)

{

        self.

name

=

name

   

}

}

// Address

class

Address

{

    var buildingName

:

String

?

     

// Building name, optional

    var buildingNumber

:

String      

// House number

    var street

:

String              

// Street

    init

(

buildingNumber

:

String, street

:

String

)

{

        self.

buildingNumber

=

buildingNumber

        self.

street

=

street

   

}

   

// Return the address identifier: if there's a building name, use "building name + house number"

    func buildingIdentifier

(

)

String

?

{

       

if

let buildingName

=

buildingName

{

           

return

"(buildingName) (buildingNumber)"

       

}

else

{

           

return

buildingNumber

       

}

   

}

}

// Residence

class

Residence

{

    var rooms

:

[

Room

]

=

[

]

         

// Room list, empty array by default

    var address

:

Address

?

         

// Address, may be nil

    var numberOfRooms

:

Int

{

       

// Computed property: number of rooms

       

return

rooms.

count

   

}

    subscript

(

i

:

Int

)

Room

{

   

// Subscript: get a room by index

       

return

rooms

[

i

]

   

}

    func printNumberOfRooms

(

)

{

        print

(

"Number of rooms: (numberOfRooms)"

)

   

}

}

// Person

class

Person

{

    var residence

:

Residence

?

     

// Residence, may be nil

}

Here residence and address are optional types—exactly what optional chaining is meant to handle.

The result of optional chaining is always an optional

Optional chaining doesn't change the original type; it just wraps another layer of optional around it.

Expression Member's original type Optional chaining result type
person.residence Residence? Residence?
person.residence?.numberOfRooms Int Int?
person.residence?.printNumberOfRooms() Void Void?
person.residence?[0].name String String?

Note:Even if numberOfRooms If it is itself Int(non-optional), then accessing it through optional chaining also yields Int?. So to get the value you must use if let or ?? to unwrap it.


Accessing properties through optional chaining

When residence is nil, person.residence?.numberOfRooms simply returns nil without accessing an empty object.

Example

let runoob

=

Person

(

)

// residence is still nil, so the whole chain returns nil

if

let roomCount

=

runoob.

residence

?

.

numberOfRooms

{

    print

(

"Runoob has (roomCount) rooms"

)

}

else

{

    print

(

"Runoob has no residence"

)

}

// Assign a value to residence and try again

let residence

=

Residence

(

)

residence.

rooms

.

append

(

Room

(

name

:

"Living room"

)

)

residence.

rooms

.

append

(

Room

(

name

:

"Study"

)

)

runoob.

residence

=

residence

if

let roomCount

=

runoob.

residence

?

.

numberOfRooms

{

    print

(

"Runoob has (roomCount) rooms"

)

}

else

{

    print

(

"Runoob has no residence"

)

}

Running the above code produces the following output:



Runoob 没有住所

Runoob 有 2 个房间

Note:runoob is declared with let , but runoob.residence = residence still compiles. Because let only forbids changing runoob this reference itself; properties inside the class instance can still be modified.


Calling methods through optional chaining

Put the question mark before the method name, and the method becomes "call only if it exists".

On success the return value is wrapped as Void?, so you can use != nil to tell whether the method actually ran.

Example

// The return type of printNumberOfRooms() is Void,

// after calling through optional chaining it becomes Void?, which can be compared with nil

if

runoob.

residence

?

.

printNumberOfRooms

(

)

!

=

nil

{

    print

(

"Method call succeeded"

)

}

else

{

    print

(

"Method call failed"

)

}

// A person with no residence

let nobody

=

Person

(

)

if

nobody.

residence

?

.

printNumberOfRooms

(

)

!

=

nil

{

    print

(

"Method call succeeded"

)

}

else

{

    print

(

"Method call failed"

)

}

Running the above code produces the following output:



房间数量:2

方法调用成功

方法调用失败

If the method itself has a return value, such as String, calling it through optional chaining likewise yields String?.


Accessing subscripts through optional chaining

The question mark for a subscript goes before the square brackets: residence?[0].

Note that the question mark in ?[0] applies to residence, not to the array element.

Example

// Subscript via optional chaining: returns nil when residence is nil

if

let firstRoomName

=

runoob.

residence

?

[

0

]

.

name

{

    print

(

"The first room is: (firstRoomName)"

)

}

else

{

    print

(

"Cannot get the first room"

)

}

// rooms itself is not optional, so rooms[0] needs no question mark

if

let secondRoomName

=

runoob.

residence

?

.

rooms

[

1

]

.

name

{

    print

(

"The second room is: (secondRoomName)"

)

}

else

{

    print

(

"Cannot get the second room"

)

}

Running the above code produces the following output:



第一个房间是:客厅

第二个房间是:书房

Note:Optional chaining can only prevent nil crashes, not out-of-bounds array access. If residence?.rooms[99] the subscript goes out of range, the program still crashes.


Multiple levels of optional chaining

One level of optional chaining can be followed by another, forming a multi-level chain.

If any link in the chain is nil, the whole expression short-circuits to nil and later members are not accessed.

Example

// Give the residence an address

let address

=

Address

(

buildingNumber

:

"100"

, street

:

"www.runoob.com"

)

address.

buildingName

=

"RUNOOB Building"

runoob.

residence

?

.

address

=

address

// Three-level chain: Person → Residence → Address → buildingIdentifier()

if

let identifier

=

runoob.

residence

?

.

address

?

.

buildingIdentifier

(

)

{

    print

(

"Address identifier: (identifier)"

)

}

else

{

    print

(

"Cannot get the address identifier"

)

}

// Use an address with no building name; buildingIdentifier() takes the other branch

let simpleAddress

=

Address

(

buildingNumber

:

"200"

, street

:

"www.runoob.com"

)

runoob.

residence

?

.

address

=

simpleAddress

print

(

"Address identifier: (runoob.residence?.address?.buildingIdentifier() ?? "

None

")"

)

// Clear the residence; the chain breaks at the second level

let emptyPerson

=

Person

(

)

print

(

"Address of empty residence: (String(describing: emptyPerson.residence?.address?.street))"

)

Running the above code produces the following output:



地址标识:RUNOOB 大厦 100

地址标识:200

空住所的地址:nil


Combining optional chaining with the nil-coalescing operator

Optional chaining always returns an optional; its most common partner is the nil-coalescing operator ??.

?? provides a default value when the left side is nil, turning the result back into a non-optional type.

Example

// With a residence: get the real count

print

(

"Number of rooms (default 0): (runoob.residence?.numberOfRooms ?? 0)"

)

// No residence: returns the default value 0

let emptyPerson

=

Person

(

)

print

(

"Rooms for empty residence: (emptyPerson.residence?.numberOfRooms ?? 0)"

)

// Use ?? as a fallback for strings

print

(

"Street: (runoob.residence?.address?.street ?? "

Not filled in

")"

)

print

(

"Building name: (runoob.residence?.address?.buildingName ?? "

Not filled in

")"

)

Running the above code produces the following output:



房间数量(默认 0):2

空住所房间数:0

街道:www.runoob.com

楼名:未填写

When you need to distinguish "value is nil" from "value is 0", you can't use ?? to flatten the result into a non-optional; use if let instead.


Optional chaining assignment

Optional chaining can also appear on the left side of an assignment, to assign to a property.

If the chain breaks, the assignment doesn't happen, and the expression on the right side isn't evaluated either, so no extra side effects occur.

Example

// Use a counter to see whether the right-side expression is evaluated

var createdCount

=

0

func makeAddress

(

_ street

:

String

)

Address

{

    createdCount

=

1

   

return

Address

(

buildingNumber

:

"1"

, street

:

street

)

}

// residence is nil, so the chain breaks at the first step

let someone

=

Person

(

)

someone.

residence

?

.

address

=

makeAddress

(

"Will not be executed"

)

print

(

"Address was created (createdCount) times"

)

// Assign to residence first; then the optional chaining assignment takes effect

let other

=

Person

(

)

other.

residence

=

Residence

(

)

other.

residence

?

.

address

=

makeAddress

(

"www.runoob.com"

)

print

(

"Address was created (createdCount) times"

)

print

(

"other's street: (other.residence?.address?.street ?? "

None

")"

)

Running the above code produces the following output:



Address 被创建了 0 次

Address 被创建了 1 次

other 的街道:www.runoob.com

Taking advantage of this, you can add optional chaining to "setup work that's only needed when the object exists", saving an if check.


Common questions

The following questions are the most common when first learning optional chaining.

Why does Int become Int?

Because the result of optional chaining must represent "the chain broke", the result always gets another layer of optional, whether or not the member was originally optional.

Just use if let, guard let, or ?? to unwrap the value.

How to choose between optional chaining and forced unwrapping !

Optional chaining quietly returns nil when the value is nil, while forced unwrapping crashes outright.

Only consider using ! when you're 100% sure the value isn't nil, or when you've already checked with if let.

How to check the result of a method call

A method returning Void yields Void? when called through optional chaining, so you can write person.residence?.printNumberOfRooms() != nil.

If you only care whether the call happened, this form is more compact than first checking residence != nil.

Can optional chaining be used consecutively on optionals of different types?

Yes. Each link only cares "is this optional currently nil"; differing types don't affect the chain.

For example, in person.residence?.address?.buildingIdentifier(), the three links are Residence?, Address?, and the return value String?.

Can optional chaining replace nil checks?

Not entirely. Optional chaining only handles "a link in the chain is nil"; it doesn't check other runtime errors like out-of-bounds arrays or failed type casts.

When you need different branch logic in these scenarios, you still need explicit checks with if let, guard let, or switch.