I have a protocol that I've created (in Swift 4.2), and one of its requirements is a property that is of the same type as the protocol itself.
As an example, I have a protocol defined like so:
protocol A {
var a: A? { get set }
}
I have several Models that conform to this protocol:
class Model1: A {
var a: A?
}
class Model2: A {
var a: A?
}
For one of my models, I need to satisfy the protocol requirement by being more specific for the property defined by variable a
(i.e. the variable with the protocol type). So for example I may want to implement Model2
as:
class Model2: A {
var a: Model1?
}
In this case since Model1
conforms to the protocol A
you would expect this to be able to satisfy the protocol requirement, however I get an error instead:
Type 'Model2' does not conform to protocol 'A'
Why is this happening, and what can I do to make it work as described above?
Appendix
I've modelled the above scenario in an Xcode Playground and here is a screenshot of the error I'm seeing.
d
actually need to be settable? If it's not settable, this is straightforward. If it is settable, what would you wanta.d = a
to do ifa
were of typeA
, but implemented asModel2
? – Rob Napier{ get set }
requirement this is unsound, as the protocolA
says you can assign anyA?
value tovar a
, butModel2
'svar a
is of typeModel1?
. However for a{ get }
requirement, this is reasonable but currently isn't supported. – Hamish