Why should not directly extend UIView or UIViewController?

前端 未结 1 361
萌比男神i
萌比男神i 2020-12-10 21:21

I saw this question, with this code:

protocol Flashable {}

extension Flashable where Self: UIView 
{
    func flash() {
        UIView.animate(withDuration:         


        
相关标签:
1条回答
  • 2020-12-10 21:52

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

    0 讨论(0)
提交回复
热议问题