在Swift 4中,你能写一个只适用于遵守多种协议的东西的扩展吗?

In Swift 4, can you write an extension that applies only to things that adhere to multiple protocols?

考虑这些协议

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 的扩展,因为它遵守两种协议。

None这些作品,当然...

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)")
    }
}

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

您可以为其中一种协议定义受限扩展:

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'

我总是通过创建一个继承自其他协议的新协议来解决这些问题。

protocol NamedValueThing: NamedThing, ValuedThing { }
extension TestThingC: NamedValueThing { }

extension NamedValueThing {
    func test() {
        print("\(value) \(name)")
    }
}

//TestThingA().test() //error: value of type 'TestThingA' has no member 'test'
//TestThingB().test() //error: value of type 'TestThingB' has no member 'test'
TestThingC().test() //4 TestThing