🔥 옵셔널 체이닝을 통한 메서드 호출

470자
5분

Swift에서는 옵셔널 체이닝을 사용하여 옵셔널 값에 대해 메서드를 호출할 수 있습니다. 이를 통해 메서드 호출이 성공적으로 이루어졌는지 확인할 수 있지요. 심지어 메서드가 반환 값을 정의하지 않은 경우에도 가능합니다.

Residence 클래스에는 numberOfRooms의 현재 값을 출력하는 printNumberOfRooms() 메서드가 있습니다. 이 메서드는 다음과 같이 생겼어요:

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

이 메서드는 반환 타입을 지정하지 않습니다. 그러나 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."를 출력합니다.
swift

옵셔널 체이닝을 통해 속성을 설정하려고 할 때도 마찬가지입니다. Accessing Properties Through Optional Chaining의 예제에서는 residence 속성이 nil임에도 불구하고 john.residence에 대해 address 값을 설정하려고 했죠. 옵셔널 체이닝을 통해 속성을 설정하려는 모든 시도는 Void? 타입의 값을 반환하므로, nil과 비교하여 속성이 성공적으로 설정되었는지 확인할 수 있습니다:

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."를 출력합니다.
swift

실제로 코드를 작성해 보면서 옵셔널 체이닝과 메서드 호출에 대해 더 깊이 이해해 보는 것은 어떨까요? 다음은 Residence 클래스와 Person 클래스를 정의하고, 옵셔널 체이닝을 사용하여 메서드를 호출하는 예제 코드입니다:

class Residence {
    var numberOfRooms = 1
 
    func printNumberOfRooms() {
        print("The number of rooms is \(numberOfRooms)")
    }
}
 
class Person {
    var residence: Residence?
}
 
let john = Person()
 
// john의 residence는 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."를 출력합니다.
 
// residence를 할당한 후에는 메서드 호출이 성공합니다.
john.residence = Residence()
 
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 possible to print the number of rooms."를 출력합니다.
// "The number of rooms is 1"도 함께 출력됩니다.
swift

이 예제 코드를 통해 옵셔널 체이닝을 사용하여 메서드를 호출하는 방법과 그 결과를 확인하는 과정을 자세히 살펴볼 수 있었습니다. 옵셔널 체이닝은 옵셔널 값에 대해 안전하게 작업할 수 있는 강력한 도구이므로, Swift 코드를 작성할 때 적극적으로 활용해 보시기 바랍니다!