Search code examples
swiftinheritanceswiftuisubclassreturn-type

Swift inheritance function return type can't be sub-type


Consider the following code:

class A {}
class B: A {}
protocol P {
    var a: A {get}
}
class P1: P {
    let a: A = B() // No problem
}
class P2: P {
    let a: B = B() // Can't compile!!
}

Since B is a sub class of A, why can't we make B as return type of var a ?


Solution

  • You cannot do that because P protocol specifically asks the conforming class to have a property of type A.

    You can always use associatedtype and generics in your protocol:

    class A {}
    class B: A {}
    protocol P {
        associatedtype T: A
        var a: T { get }
    }
    class P1: P {
        let a: A = B()
    }
    class P2: P {
        let a: B = B()
    }
    

    Keep in mind though, that if you do that you cannot use P protocol as a type directly but only with generics:

    enter image description here