1. 实现过程
swift本身并不支持多继承,但我们可以根据已有的API去实现.
swift中的类可以遵守多个协议,但是只可以继承一个类,而值类型(结构体和枚举)只能遵守单个或多个协议,不能做继承操作.
多继承的实现:协议的方法可以在该协议的extension
中实现
protocol Behavior { func run() } extension Behavior { func run() { print("Running...") } } struct Dog: Behavior {} let myDog = Dog() myDog.run() // Running...
无论是结构体还是类还是枚举都可以遵守多个协议,所以多继承就这么做到了.
2. 通过多继承为UIView
扩展方法
// MARK: - 闪烁功能 protocol Blinkable { func blink() } extension Blinkable where Self: UIView { func blink() { alpha = 1 UIView.animate( withDuration: 0.5, delay: 0.25, options: [.repeat, .autoreverse], animations: { self.alpha = 0 }) } } // MARK: - 放大和缩小 protocol Scalable { func scale() } extension Scalable where Self: UIView { func scale() { transform = .identity UIView.animate( withDuration: 0.5, delay: 0.25, options: [.repeat, .autoreverse], animations: { self.transform = CGAffineTransform(scaleX: 1.5, y: 1.5) }) } } // MARK: - 添加圆角 protocol CornersRoundable { func roundCorners() } extension CornersRoundable where Self: UIView { func roundCorners() { layer.cornerRadius = bounds.width * 0.1 layer.masksToBounds = true } } extension UIView: Scalable, Blinkable, CornersRoundable {} cyanView.blink() cyanView.scale() cyanView.roundCorners()