swift - 在 Swift 4 中,您能否编写仅适用于遵守多种协议(protocol)的事物的扩展?

标签 swift protocols extension-methods swift4 swift-extensions

考虑这些协议(protocol)

protocol NamedThing{
    var name:String{ get }
}

protocol ValuedThing{

    associatedtype ValueType

    var value:ValueType{ get }
}

还有这些结构...

struct TestThingA : NamedThing {
    let name = "TestThing"
}

struct TestThingB : ValuedThing {

    typealias ValueType = Int

    let value = 4
}

struct TestThingC : NamedThing, ValuedThing {

    typealias ValueType = Int

    let name = "TestThing"
    let value = 4
}

我正在尝试编写一个仅适用于结构 TestThingC 的扩展,因为它遵守这两种协议(protocol)。

当然,这些都不起作用......

extension NamedThing & ValuedThing{
    func test(){
        print("Named thing \(name) has a value of \(value)")
    }
}

extension Any where NamedThing & ValuedThing {
    func test(){
        print("Named thing \(name) has a value of \(value)")
    }
}

extension Any where Self is NamedThing, Self is ValuedThing{

    func test(){
        print("Named thing \(name) has a value of \(value)")
    }
}

extension Any where Self == NamedThing, Self == ValuedThing{

    func test(){
        print("Named thing \(name) has a value of \(value)")
    }
}

那么如何编写适用于同时(多个)协议(protocol)的项目的扩展?

最佳答案

您可以为其中一种协议(protocol)定义一个受限制的扩展:

extension NamedThing where Self: ValuedThing {
    func test(){
        print("Named thing \(name) has a value of \(value)")
    }
}

TestThingC().test() // compiles

TestThingA().test() // error: Type 'TestThingA' does not conform to protocol 'ValuedThing'
TestThingB().test() // error: Value of type 'TestThingB' has no member 'test'

关于swift - 在 Swift 4 中,您能否编写仅适用于遵守多种协议(protocol)的事物的扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47894985/

相关文章:

ios - XCode 自动布局在 'View as' 中未选择的设备上无法正常工作

ios - 创建符合另一个协议(protocol)的协议(protocol)变量

c# - 为什么在 IEnumerables 上使用标准扩展方法

c# - 使通用扩展方法正常工作的问题

ios - 列出重新加载动画故障

Swift 单例与静态属性/方法

ios - 在协议(protocol)定义的方法参数中调用的类的前向声明

ios - 如何创建扩展文件并在 iOS Swift 3 的 View Controller 中调用它?

ios - 如何将多个观察者绑定(bind)到一个 ControlProperty

swift - 具有通用功能和关联类型的协议(protocol)