Is it possible to add protocol compliance to a different protocol by way of an extension?
For instance we would like A to comply with B:
protocol A {
You can make A
inherits from B
:
protocol A: B { var a: String { get } }
protocol B { var b: String { get } }
// Default implementation of property b
extension A {
var b: String { get { return "PropertyB" } }
}
class MyClass: A {
var a: String { get { return "PropertyA" } }
func printA(obj: A) {
print(obj.a)
printB(obj)
}
func printB(obj: B) {
print(obj.b)
}
}
let obj = MyClass()
obj.printA(obj)
Since A
inherits from B
, every property in B
is available in A
.
When extending A
, you could specify that the type also conforms to B
:
extension A where Self: B {
var b : UIView {
return self.a
}
}
Then make your type conform to A
and B
, e.g.
struct MyStruct : A, B {
var a : UIView {
return UIView()
}
}
Due to the protocol extension, instances of MyStruct
will be able to use a
and b
, even though only a
was implemented in MyStruct
:
let obj = MyStruct()
obj.a
obj.b