Why doesn't swift support return type covarience in methods defined in protocols? e.g
class Base { }
class Derived : Base { }
protocol Requirement {
var someVariable : Base { get }
}
struct MyStruct : Requirement{
let someVariable : Derived
}
The compiler thorws an error that MyStruct doesn't conform to protocol Requirement. As far I know MyStruct fulfils all the requirements of LSP, so I am wondering why is this not allowed in Swift?
Context is important here, so I don't know if this will get you what you want.
My answer is use associatedtype
.
Start with the same setup
class Base { }
class Derived: Base { }
This time, I'll define a type in the protocol which must be some kind of Base
.
protocol Requirement {
associatedtype KindOfBase: Base
var someVariable: KindOfBase { get }
}
Now you get what you want.
struct MyStruct: Requirement {
let someVariable: Derived
}
struct MyStruct2: Requirement {
let someVariable: Base
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With