Overriding delegate property of UIScrollView in Swift (like UICollectionView does)

后端 未结 6 2137
春和景丽
春和景丽 2021-02-01 02:36

UIScrollView has a delegate property which conforms to UIScrollViewDelegate

protocol UIScrollViewDelegate : NSObjectProtocol {
    //...
}
class UIScrollView : U         


        
6条回答
  •  感情败类
    2021-02-01 02:49

    Consider the following situation:

    class BaseProp {}
    
    class Base {
        var prop: BaseProp
    }
    

    Then if you do this:

    class DerivedProp: BaseProp {}
    
    class Derived: Base {
        override var prop: DerivedProp
    }
    

    Then if would break the subclassing principles (namely, the Liskov Substitution Principle). Basically what you are doing is limiting the scope of "var prop" from wider "BaseProp" type to a more narrow "DerivedProp" type. Then this kind of code would be possible, which does not make sense:

    class UnrelatedProp: BaseProp {}
    
    let derived = Derived()
    let base = derived as Base
    base.prop = UnrelatedProp()
    

    Note that we are assigning an instance of UnrelatedProp to the property, which does not make sense for the Derived instance which we actually operate with. ObjectiveC allows such kind of ambiguity, but Swift doesn't.

提交回复
热议问题