gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:05:30 24 4
gpt4 key购买 nike

我看到了这个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:

扭曲它
  • 是不是为了让我们增强我们的意图,当其他开发人员来的时候,他们会看到嘿这个类符合 Flashable、Dimmable 等?
  • 我们的 UIView 也会有单独的有意义的扩展吗?而不是对 UIView 或 UIViewController 进行不同的未命名扩展?
  • 是否有任何关于 POP 主题的具体 Apple 指南?我见过那里的开发人员这样做,但不确定为什么...

最佳答案

这种方法比直接使用 UIView 更可取,如

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

因为它让程序员决定他们希望将哪些 UIView 子类制作成 Flashable,而不是将 flash 功能“批发”到所有 UIViews:

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

从本质上讲,这是一种“选择加入”的方法,而另一种方法则强制功能无法“选择退出”。

关于swift - 为什么不应该直接扩展 UIView 或 UIViewController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41706504/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com