为什么不应该直接扩展 UIView 或 UIViewController?

Why should not directly extend UIView or UIViewController?

我看到这个 question,代码如下:

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,如

extension UIView {
    func flash() {
        ...
    }
}

因为它让程序员决定他们希望创建哪些 UIView 子类 Flashable,而不是向所有 UIView 添加 flash 功能 "wholesale" :

// This class has flashing functionality
class MyViewWithFlashing : UIView, Flashable {
    ...
}
// This class does not have flashing functionality
class MyView : UIView {
    ...
}

本质上,这是一种 "opt in" 方法,而替代方法强制功能无法 "opt out"。