考虑这些协议(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/