我看到了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:
答案 0 :(得分:6)
这种方法比直接使用UIView
更好,如
extension UIView {
func flash() {
...
}
}
因为它允许程序员决定他们希望制作UIView
个子类Flashable
,而不是向所有flash
添加UIView
功能“批发”:
// This class has flashing functionality
class MyViewWithFlashing : UIView, Flashable {
...
}
// This class does not have flashing functionality
class MyView : UIView {
...
}
基本上,这是一种“选择加入”的方法,而另一种方法强制实现功能而无法“选择退出”。