在Swift中编写Kotlin的by-clause(a.k.a。类委派)的正确方法是什么?

问题描述 投票:1回答:1

我需要在Swift中重新编写一个像这样定义的Kotlin类:

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

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

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

最简洁的方法是什么?

swift design-patterns kotlin software-design
1个回答
2
投票

如您所知,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.

如何?

© www.soinside.com 2019 - 2024. All rights reserved.