我需要在 Swift 中重新编码一个如下定义的 Kotlin 类:
class A(private val foo: FooInterface = FooBase()) : FooInterface by foo {
...
}
实现这一目标的唯一方法是使用 FooInterface
协议(protocol)直接扩展类 A 并将所有调用重定向到本地私有(private) Foo
实例吗?
extension A: FooInterface {
func fooFun1() {
self.privateFooInstance.fooFun1()
}
}
最简洁的方法是什么?
最佳答案
正如您所知,Swift 不直接支持类委托(delegate)。
因此,您可能需要比 Kotlin 更多的代码,Kotlin 直接支持委托(delegate)。但是,您可以添加委派的默认实现,而不是扩展每个实现该协议(protocol)的类。
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.
怎么样?
关于swift - 在 Swift 中编写 Kotlin 的 by-clause(又名类委托(delegate))的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55621147/