“多态”(Polymorphism)是面向对象编程(OOP)的三大核心特性之一,和“封装”“继承”并列,让程序更灵活、可扩展、可维护。
多态指的是相同接口、不同表现。
在Swift中,可以使用父类(或协议)类型来引用子类(或具体实现)对象,并在运行时执行不同的行为。
示例:
class Animal {
func makeSound() {
print("Animal makes sound")
}
}
class Dog: Animal {
override func makeSound() {
print("Dog barks")
}
}
class Cat: Animal {
override func makeSound() {
print("Cat meows")
}
}
let animals: [Animal] = [Dog(), Cat(), Animal()]
for animal in animals {
animal.makeSound()
}
输出内容为:
Dog barks
Cat meows
Animal makes sound
调用的是 animal.makeSound() ——都是 Animal 类型!
但运行时,Swift 会根据实际对象类型(Dog、Cat、Animal)调用不同的方法。
这就是多态:一种接口,多种行为。
Swift实现多态
1、子类重写(override):父类调用子类方法。
let animal: Animal = Dog()
animal.makeSound() // Dog barks
虽然变量类型是 Animal,但调用的是子类 Dog 的方法。
2、协议多态(Protocol-Oriented):多个类/结构体实现同一协议。
protocol Drawable {
func draw()
}
struct Circle: Drawable {
func draw() { print("Draw a circle") }
}
struct Rectangle: Drawable {
func draw() { print("Draw a rectangle") }
}
let shapes: [Drawable] = [Circle(), Rectangle()]
shapes.forEach { $0.draw() }
通过协议类型 [Drawable] 统一调用不同类型对象的方法。
3、泛型多态(Generic Polymorphism),同一函数处理不同类型数据。
func printItem<T>(_ item: T) {
print(item)
}
printItem(123)
printItem("Hello")
printItem([1, 2, 3])
函数需要写一次,就可以接收任意类型 —— 这是编译时多态。
多态的优点
1、可扩展性强:添加新子类或实现不需要改动旧代码;
2、代码复用:通用接口可统一处理多个类型;
3、解耦合:调用方不关心对象的具体类型,只关心“能做什么”。
总结
多态让代码变得更通用、更灵活,可以在同一接口下切换不同实现,而无需修改调用逻辑。
相关文章
1、Swift继承:https://fangjunyu.com/2025/07/30/swift%e7%bb%a7%e6%89%bf/
2、Swift封装:https://fangjunyu.com/2025/07/30/swift%e5%b0%81%e8%a3%85/
3、Swift UI 深入理解泛型:https://fangjunyu.com/2024/10/04/swift-ui-%e6%b7%b1%e5%85%a5%e7%90%86%e8%a7%a3%e6%b3%9b%e5%9e%8b/
4、Swift protocol协议教程:https://fangjunyu.com/2024/12/01/swift-protocol%e5%8d%8f%e8%ae%ae%e6%95%99%e7%a8%8b/