swift - 在 Swift 中编写 Kotlin 的 by-clause(又名类委托(delegate))的正确方法是什么?

标签 swift design-patterns kotlin software-design

我需要在 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/

相关文章:

Swift:在 Storyboard中更改 UI TextView 大小后,textView 方法 "scrollRangeToVisible"不起作用?

c++ - 设计模式会破坏抽象吗?

oop - 哪种设计模式最适合用于控制一系列步骤?

swift - Kotlin 相当于 %@ 在 swift

android - Kotlin 中的 Firebase firestore 权限被拒绝

ios - ActionSheetPicker 用于 ActionSheetPicker 的无效目标/操作组合

iphone - 在 TableView / Collection View 中采用拖放功能在 iPhone 上不起作用

c++ - 非确定性操作的设计模式(nondet.factory?)

ANDROID 如何通过适配器将我的 mutableLiveData 绑定(bind)到我的 Recyclerview

ios - Deezer SDK IOS 按 id 播放轨道