扩展现有协议以使用默认工具实现另一个协议 [英] Extend existing protocols to implement another protocol with default implements
问题描述
是否可以通过扩展将协议合规性添加到不同的协议中?
Is it possible to add protocol compliance to a different protocol by way of an extension?
例如,我们希望 A 遵守 B:
For instance we would like A to comply with B:
protocol A {
var a : UIView {get}
}
protocol B {
var b : UIView {get}
}
我想为类型 A 的对象提供 B 的默认实现(合规性)
I want to give a default implementation (compliance) of B to objects of type A
// This isn't possible
extension A : B {
var b : UIView {
return self.a
}
}
动机是在需要 B 的情况下重用 A 的对象而不创建我自己的桥"
The motivation being to reuse objects of A in cases where a B is required without creating my own "bridge"
class MyClass {
func myFunc(object : A) {
...
...
let view = object.a
... do something with view ...
myFunc(object) // would like to use an 'A' without creating a 'B'
}
func myFunc2(object : B) {
...
...
let view = object.b
... do something with view ...
}
}
作为旁注,我们可以扩展一个类来实现一个协议
As a side note we can extend a class to implement a protocol
class C {
let C : UIView
}
// this will work
extension C : B {
var B : UIView {
return self.c
}
}
和协议可以提供默认实现
and protocols can give default implementations
extension A {
// a default implementation
var a : UIView {
return UIView()
}
}
推荐答案
在扩展A
时,可以指定类型也符合B
:
When extending A
, you could specify that the type also conforms to B
:
extension A where Self: B {
var b : UIView {
return self.a
}
}
然后让你的类型符合A
和B
,例如
Then make your type conform to A
and B
, e.g.
struct MyStruct : A, B {
var a : UIView {
return UIView()
}
}
由于协议扩展,MyStruct
的实例将能够使用 a
和 b
,即使只有 a
在 MyStruct
中实现:
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
这篇关于扩展现有协议以使用默认工具实现另一个协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!