我需要在Swift中重新编写一个像这样定义的Kotlin类:
class A(private val foo: FooInterface = FooBase()) : FooInterface by foo {
...
}
实现这一目标的唯一方法是使用FooInterface
协议直接扩展A类并将所有调用重定向到本地私有Foo
实例吗?
extension A: FooInterface {
func fooFun1() {
self.privateFooInstance.fooFun1()
}
}
最简洁的方法是什么?
如您所知,Swift没有直接支持类授权。
因此,您可能需要比Kotlin更多的代码,Kotlin直接支持委派。但是,您可以添加默认的委托实现,而不是扩展实现协议的每个类。
protocol FooInterface {
func fooFun1()
//...
}
protocol FooDelegateable {
var fooDelegate: FooInterface {get}
}
extension FooInterface where Self: FooDelegateable {
func fooFun1() {
self.fooDelegate.fooFun1()
}
//...
}
struct SomeFoo: FooInterface {
func fooFun1() {
print("FooInterface is delegated to SomeFoo.")
}
}
class A: FooInterface, FooDelegateable {
private let foo: FooInterface
//FooDelegateable
var fooDelegate: FooInterface {return foo}
init(_ foo: FooInterface) {
self.foo = foo
}
//...
}
let a = A(SomeFoo())
a.fooFun1() //->FooInterface is delegated to SomeFoo.
如何?