Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
783 views
in Technique[技术] by (71.8m points)

swift - 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)
            }
        }
    }
}

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:

  • Is it so that we increase our intent and when other developers come they would see that hey this class is conforming to Flashable, Dimmable, etc?
  • Also our UIView would have separate meaningful extensions? Instead of different unNamed extensions to UIView or UIViewController?
  • Are there any specific Apple guidelines on this subject for POP? I've seen there developer doing it this way but not sure of the why...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This approach is preferable to using UIView directly, as in

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

because it lets programmers decide which UIView subclasses they wish to make Flashable, as opposed to adding flash functionality "wholesale" to all UIViews:

// 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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...