是否可以添加条件,其中协议由任一类确认,在 where 子句 Self 中提供多个选项

Ank*_*arg 0 ios swift

让我们假设我们有

protocol xyz {

}

class A: xyz {
}

class B: xyz {
}

class C: xyz{
}
Run Code Online (Sandbox Code Playgroud)

仅当实例属于 A 或 B 类类型时才调用 xyz 的扩展

extension xyz where Self: A, B {

}
Run Code Online (Sandbox Code Playgroud)

Luc*_*tti 5

因此,当 Self 是 A 或 B 时,您想定义协议 XYZ 的扩展,对吗?

答案是:你不能。

然而

你可以通过做这样的事情来获得类似的结果

protocol XYZ { }
protocol AOrB: XYZ { }

class A: AOrB { }
class B: AOrB { }
class C: XYZ { }

extension XYZ where Self: AOrB {
    func foo() { }
}

A().foo()
B().foo()
Run Code Online (Sandbox Code Playgroud)