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()