Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return type covariance in protocol methods [duplicate]

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?

like image 629
salman140 Avatar asked May 11 '16 19:05

salman140


1 Answers

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
}
like image 142
Jeffery Thomas Avatar answered Nov 15 '22 18:11

Jeffery Thomas