[swift] 프로토콜을 통한 타입 캐스팅

프로토콜은 특정한 동작이나 속성에 대한 요구사항을 정의하는데 사용됩니다. 스위프트에서 프로토콜은 다른 타입으로 캐스팅되거나 동작을 수행하는 데 유용하게 활용될 수 있습니다.

프로토콜과 타입 캐스팅

프로토콜은 상속과 함께 사용될 때 다형성(polymorphism)을 제공합니다. 이는 서로 다른 타입으로 캐스팅되거나 동일한 인터페이스를 통해 동작할 수 있는 능력을 의미합니다.

protocol MyProtocol {
    func myMethod()
}

class MyClass: MyProtocol {
    func myMethod() {
        print("MyClass의 메서드 호출")
    }
}

class YourClass: MyProtocol {
    func myMethod() {
        print("YourClass의 메서드 호출")
    }
}

let myInstance: MyProtocol = MyClass()
myInstance.myMethod() // 출력: "MyClass의 메서드 호출"

let yourInstance: MyProtocol = YourClass()
yourInstance.myMethod() // 출력: "YourClass의 메서드 호출"

위 예제에서 MyClassYourClass는 모두 MyProtocol을 준수하므로, 프로토콜을 통해 두 클래스의 인스턴스를 동작시킬 수 있습니다.

프로토콜 타입 캐스팅

프로토콜을 통한 타입 캐스팅은 인스턴스를 프로토콜 타입으로 변환하는 것을 의미합니다. 이를 통해 프로토콜을 준수하는 다양한 타입을 일관된 방식으로 처리할 수 있습니다.

func doSomething(with instance: MyProtocol) {
    if let myClassInstance = instance as? MyClass {
        print("MyClass 인스턴스와 연관된 작업 수행")
    } else if let yourClassInstance = instance as? YourClass {
        print("YourClass 인스턴스와 연관된 작업 수행")
    }
}

let instance1: MyProtocol = MyClass()
doSomething(with: instance1) // 출력: "MyClass 인스턴스와 연관된 작업 수행"

let instance2: MyProtocol = YourClass()
doSomething(with: instance2) // 출력: "YourClass 인스턴스와 연관된 작업 수행"

위 예제에서 doSomething 함수는 MyProtocol 타입의 인자를 받아 해당 인스턴스가 MyClass인지, YourClass인지 여부를 타입 캐스팅을 통해 판별하고 작업을 수행합니다.

프로토콜을 통한 타입 캐스팅을 활용하여 코드의 유연성을 높이고, 재사용성을 증가시킬 수 있습니다.

이상으로 프로토콜을 통한 타입 캐스팅에 대한 내용을 정리해보았습니다.