为什么不应该直接扩展UIView或UIViewController? [英] Why should not directly extend UIView or UIViewController?
问题描述
I saw this question, with this code:
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:
And I wonder why do we you not just directly just extend UIView
? Or in similar cases extend UIViewController
why twist it around with a where Self:
- 是否是为了增加我们的意图,当其他开发人员来访时,他们会看到嘿此类符合Flashable,Dimable等标准吗?
- 我们的UIView还会有单独的有意义的扩展吗?而不是UIView或UIViewController的不同的未命名扩展?
- 关于POP这个主题,苹果是否有任何具体的指导方针?我见过那里的开发人员以这种方式这样做,但不确定为什么...
推荐答案
这种方法比直接使用UIView
更可取,例如
This approach is preferable to using UIView
directly, as in
extension UIView {
func flash() {
...
}
}
因为它使程序员可以决定要创建Flashable
的哪些UIView
子类,而不是将flash
功能批发"添加到所有UIView
:
because it lets programmers decide which UIView
subclasses they wish to make Flashable
, as opposed to adding flash
functionality "wholesale" to all UIView
s:
// This class has flashing functionality
class MyViewWithFlashing : UIView, Flashable {
...
}
// This class does not have flashing functionality
class MyView : UIView {
...
}
从本质上讲,这是一种选择加入"方法,而另一种方法则强制了该功能而没有选择退出"的方法.
Essentially, this is an "opt in" approach, while the alternative approach forces the functionality without a way to "opt out".
这篇关于为什么不应该直接扩展UIView或UIViewController?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!