Hon*_*ney 3 protocols swift swift-extensions protocol-oriented
我用这段代码看到了这个问题:
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)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
而且我想知道为什么我们不只是直接扩展UIView?或者在类似的情况下延伸UIViewController为什么用a扭转它where Self:
这种方法比UIView直接使用更好,如
extension UIView {
func flash() {
...
}
}
Run Code Online (Sandbox Code Playgroud)
因为它允许程序员决定UIView他们希望制作哪些子类Flashable,而不是flash向所有UIViews 添加"批发"功能:
// This class has flashing functionality
class MyViewWithFlashing : UIView, Flashable {
...
}
// This class does not have flashing functionality
class MyView : UIView {
...
}
Run Code Online (Sandbox Code Playgroud)
从本质上讲,这是一种"选择加入"方法,而替代方法强制实现功能而无法"选择退出".
| 归档时间: |
|
| 查看次数: |
418 次 |
| 最近记录: |