如何在协议A的扩展中检查“self”是否遵循协议B?

问题描述 投票:0回答:1

设计模式看起来像这样:

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?
可以工作,但是这里有一定的模式或最佳实践吗?

swift swift-protocols
1个回答
0
投票

您需要定义“实际上不起作用”。其他人看到它有效但不理解。

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"
© www.soinside.com 2019 - 2024. All rights reserved.