设计模式看起来像这样:
protocol Base {
}
protocol A: Base {
}
protocol B: Base {
}
extension A {
func someFunc() {
if ((self as Any) is any B.Type) { // <- apparently this compiles, but doesn't return True as it's designed in extension A, not the real class that both follows A and B
print("So it also follows protocol B")
}
}
}
class finalClass: A, B {
func anotherFunc() {
someFunc()
}
}
我想检查扩展 A 的定义,调用该函数的类是否也遵循协议 B?
我意识到使用
as?
可以工作,但是这里有一定的模式或最佳实践吗?
您需要定义“实际上不起作用”。其他人看到它有效但不理解。
extension A {
func someFunc() -> String { "A" }
}
extension A where Self: B {
func someFunc() -> String { "B" }
}
final class AClass: A { }
final class ABClass: A & B { }
AClass().someFunc() // "A"
ABClass().someFunc() // "B"