在 Swift 中编写 Kotlin 的从句(a.k.a。Class 委托)的正确方法是什么?

What is the proper way to code Kotlin's by-clause (a.k.a. Class Delegation) in Swift?

我需要在 Swift 中重新编码 Kotlin class 定义如下:

class A(private val foo: FooInterface = FooBase()) : FooInterface by foo {
  ...
}

实现这一目标的唯一方法是使用 FooInterface 协议直接扩展 class A 并将所有调用重定向到本地私有 Foo 实例吗?

extension A: FooInterface {
  func fooFun1() {
    self.privateFooInstance.fooFun1()
  }
}

最简洁的方法是什么?

如您所知,Swift 不直接支持 Class 委派。

因此,您可能需要比直接支持委托的 Kotlin 更多的代码。但是,您可以为委托添加默认实现,而不是扩展每个实现协议的 class。

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.

怎么样?