蘇哲聖
蘇哲聖

Reputation: 795

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 ?

Upvotes: 2

Views: 53

Answers (2)

gcharita
gcharita

Reputation: 8347

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

Upvotes: 2

zeytin
zeytin

Reputation: 5643

class A {}
class B: A {}
protocol P {
    var a: A {get}
}

class P1: P {
    let a: A = B() // No problem
}

class P1x: P {
    let a = A() // No problem
 
}

class P1y: P {
    var a = A()
    
    let b: B = B() // No problem
}

Now your confused point :

class P2: P {
    let a: B = B() // Can't compile!
}

Because a belongs to type A not B as declared in protocol B !

Upvotes: 1

Related Questions