オプショナル値のメソッドを呼び出すため、およびメソッド呼び出しが成功するかを確認するためにオプショナルチェーンを利用することができます。

Residence クラスの printNumberOfRooms() メソッドは、numberOfRooms の現在値を出力します。次がそのメソッドです。

func printNumberOfRooms() {
    print("The number of rooms is \(numberOfRooms)")
}

このメソッドは戻り値の型を指定していません。ですが、戻り値の型が無い関数およびメソッドは、Functions Without Return Values で説明されているように、暗黙の戻り値型 Void となります。つまり、空のタプルである () の値 を返します。

オプショナルチェーンでオプショナル値のこのメソッドを呼び出す場合、オプショナルチェーンで呼び出された戻り値の型は常にオプショナル型であるため、メソッドの戻り値の型は Void ではなく Void? になります。メソッド自体には戻り値を定義していませんが、printNumberOfRooms() メソッドを呼び出せるかをチェックするために if 文を使用することができます。メソッド呼び出しが成功したかを確認するために、printNumberOfRooms() からの戻り値を nil に対して比較します。

if john.residence?.printNumberOfRooms() != nil {
    print("It was possible to print the number of rooms.")
} else {
    print("It was not possible to print the number of rooms.")
}
// "It was not possible to print the number of rooms." と出力

オプショナルチェーンでプロパティに設定しようとする場合も同じです。Accessing Properties Through Optional Chaining での例では、residence プロパティが nil でありながら、john.residence に address 値を設定しようとしています。オプショナルチェーンでプロパティに設定しようとすると、プロパティが無事に設定されたかを確認するために、nil に対して比較できる Void? 型の値を返します。

if (john.residence?.address = someAddress) != nil {
    print("It was possible to set the address.")
} else {
    print("It was not possible to set the address.")
}
// "It was not possible to set the address." と出力

Portions of this page are translations based on work created and shared by Apple and used according to terms described in the Creative Commons Attribution 4.0 International License.