我看到了这个问题,使用以下代码:
protocol Flashable {} extension Flashable where Self: UIView { func flash() { UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: { self.alpha = 1.0 //Object fades in }) { (animationComplete) in if animationComplete == true { UIView.animate(withDuration: 0.3, delay: 2.0, options: .curveEaseOut, animations: { self.alpha = 0.0 //Object fades out }, completion: nil) } } } }
我想知道为什么我们不只是直接扩展UIView?或在类似情况下扩展UIViewController为什么要用where Self:
UIView
UIViewController
where Self:
这种方法优于UIView直接使用,例如
extension UIView { func flash() { ... } }
因为它可以让程序员决定UIView他们想要创建哪些子类Flashable,而不是flash向所有ss都添加功能“批发” UIView:
Flashable
flash
// This class has flashing functionality class MyViewWithFlashing : UIView, Flashable { ... } // This class does not have flashing functionality class MyView : UIView { ... }
从本质上讲,这是一种“选择加入”方法,而另一种方法则强制执行功能而没有“选择退出”的方法。