编码Kotlin';Swift中的s by条款(又称类别授权)?

编码Kotlin';Swift中的s by条款(又称类别授权)?,swift,design-patterns,kotlin,software-design,Swift,Design Patterns,Kotlin,Software Design,我需要在Swift中重新编码定义如下的Kotlin类: class A(private val foo: FooInterface = FooBase()) : FooInterface by foo { ... } 实现这一点的唯一方法是使用Foo接口协议直接扩展类A,并将所有调用重定向到本地私有Foo实例吗 extension A: FooInterface { func fooFun1() { self.privateFooInstance.fooFun1() } }

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

class A(private val foo: FooInterface = FooBase()) : FooInterface by foo {
  ...
}
实现这一点的唯一方法是使用
Foo接口
协议直接扩展类A,并将所有调用重定向到本地私有
Foo
实例吗

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

最简洁的方法是什么?

如您所知,Swift不直接支持类委托

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.
因此,您可能需要比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.

怎么样?

谢谢!但有一点:Kotlin/Native将
FooInterface
编译为Objective-C时,它似乎不起作用,因为无法在协议扩展名中用@objc标记函数。@dimart.sp,谢谢您的评论。是的,这是真的,您不能用协议扩展实现
@objc
方法。至于现在,在这种情况下,我想不出什么简洁的东西。顺便说一句,财产委托是forums.swift.org发展过程中当前的热门话题之一,因此未来的swift中也可能包含类委托。