Why does the following code produce an error?
protocol ProtocolA {
var someProperty: ProtocolB { get }
}
protocol ProtocolB {}
class ConformsToB: Protoc
In addition to Harmish's great response, if you want to keep using the same property name on both SomeClass
and ProtocolA
, you can do
protocol ProtocolB {}
protocol ProtocolA {
var _someProperty_protocolA: ProtocolB { get }
}
extension ProtocolA {
var someProperty: ProtocolB {
return _someProperty_protocolA
}
}
class ConformsToB: ProtocolB {}
class SomeClass: ProtocolA {
// the *actual* implementation of someProperty.
var _someProperty: ConformsToB
var someProperty: ConformsToB {
// You can't expose someProperty directly as
// (SomeClass() as ProtocolA).someProperty would
// point to the getter in ProtocolA and loop
return _someProperty
}
// dummy property to satisfy protocol conformance.
var _someProperty_protocolA: ProtocolB {
return someProperty
}
init(someProperty: ConformsToB) {
self.someProperty = someProperty
}
}
let foo = SomeClass(someProperty: ConformsToB())
// foo.someProperty is a ConformsToB
// (foo as ProtocolA).someProperty is a ProtocolB
This can be useful when you are conforming to another protocol ProtocolA2
that would originally also have constraint on someProperty
as well, or when you want to hide your hack around swift limitations.
I'm now curious to know why Swift is not doing this for me directly.