1

Here is my code:

protocol base{}

protocol sub: base{}

protocol SomeProtocol{
    var a: base{get}
}

struct SomeStruct: SomeProtocol{
//    var a: base
    var a: sub
}

when I use var a: sub in Struct, I get an error:

Type 'SomeStruct' does not conform to protocol 'SomeProtocol'

I'm wondering var a: sub should conform to base protocol, but why Swift cannot write like this? Is there any better plan?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Oven.V
  • 67
  • 3

1 Answers1

2

The problem with conforming types applies to derived protocols as well. Workarounds, listed there, look like this for your code:

protocol SomeProtocol {
  associatedtype A: Base
  var a: A { get }
}

struct SomeStruct<A: Sub>: SomeProtocol {
  var a: A
}
protocol SomeProtocol {
  var a: any Base { get }
}

struct SomeStruct: SomeProtocol {
  var _a: any Sub
  var a: any Base { _a }
}