Does Swift support covariance-return-type in protocols?

80 Views Asked by At

I found here that function overriding is available in protocols. Obviously, it can be overriding of signature, not of implementation. So, if it isn't shadowing, it makes sense only for covariance/contravariance. I tried to test it and my check failed.

class Egg { }

class EasterEgg : Egg { }

protocol EggTray {
  func get_1() -> Egg;
  func get_2() -> Egg;
  func get_3() -> Egg;
  func get_4() -> Egg;
}

protocol EasterEggTray : EggTray { 
  override func get_1() -> EasterEgg;
  override func get_2() -> EasterEgg;
  override func get_3() -> EasterEgg;
  override func get_4() -> EasterEgg;
}

The error message says that 'override' is supported but the compiler can't match two functions (It ignores covariance).

error: method does not override any method from its parent protocol
override func get_1() -> EasterEgg;

note: potential overridden instance method 'get_1()' here
func get_1() -> Egg;

Covariance-return-type works for classes, but for protocols, it isn't compilable. Does Swift support covariance-return-type in protocols? If yes - How does Swift expect it to be written in code? (I know how to do it with the associated type, but it isn't what I am looking for.) If not - Why not? What is the reason why Swift doesn't support it? What is the reason for the 'override' keyword in protocols?

0

There are 0 best solutions below