[swift] 다형성

예를 들어, 동일한 동작을 가지고 있는데 내부 구현은 다른 여러 객체들이 있을 때, 이를 특정 인터페이스나 추상 클래스로 정의하고, 이를 구현한 각 객체들을 동일한 방식으로 다룰 수 있습니다. 다형성을 이용하면 코드의 유연성과 재사용성을 높일 수 있습니다.

protocol Animal {
    func makeSound()
}

class Dog: Animal {
    func makeSound() {
        print("Woof!")
    }
}

class Cat: Animal {
    func makeSound() {
        print("Meow!")
    }
}

func animalSound(animal: Animal) {
    animal.makeSound()
}

let dog = Dog()
let cat = Cat()

animalSound(animal: dog) // Output: Woof!
animalSound(animal: cat) // Output: Meow!

이 예제에서 Animal 프로토콜을 통해 DogCat 클래스를 동일한 방식으로 다룰 수 있습니다.

다형성은 객체 지향 프로그래밍의 힘을 보여주는 중요한 개념 중 하나입니다.

관련 자료: