A Swift protocol requirement that can only be satisfied by using a final class

前端 未结 4 1000
不知归路
不知归路 2020-12-05 18:41

I\'m modeling a owner/ownee scheme on Swift:

class Owner {
     // ...
}

protocol Ownee {
    var owner: Owner { get }
}
         


        
4条回答
  •  再見小時候
    2020-12-05 19:17

    What happens if Student is subclassed? The owner property remains Owner, but Student != StudentSubclass.

    By making your Student class conform to the Ownee protocol, you must satisfy the contract of the protocol. The Ownee protocol states that Owner has type constraint, such that the Owner generic type is the type that's conforming to Ownee (Student, in this case).

    If the compiler were to allow subclassing (i.e. by allowing you to not make Student final), then it would be possible for a StudentSubclass to exist. Such a subclass would inherit the Owner property, of type Owner, but Student is not the same as StudentSubclass. The Ownee protocol's contract has been breached, thus, such a subclass cannot be allowed to exist.

提交回复
热议问题