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

huangapple go评论70阅读模式
英文:

How can I check in protocol A's extension, that whether or not `self` follows protocol B?

问题

设计模式看起来像这样:

protocol Base {

}

protocol A: Base {

}

protocol B: Base {

}

extension A {
    func someFunc() {
        if ((self as Any) is any B.Type) { // <- 显然这是可以编译的,但不会返回True,因为它是在扩展A中设计的,而不是遵循A和B的真实类
            print("所以它也遵循协议B")
        }
    }
}

class finalClass: A, B {
    func anotherFunc() {
        someFunc()
    }
}

我想在扩展A的定义中检查调用该函数的类是否也遵循协议B?

我意识到使用as?可能有效,但是否有特定的模式或最佳实践?

英文:

Design patterns looks something like this:

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

I'd like to check in definition of extension A, whether or not the class calling that function, also follows protocol B?

I release that using as? could work, but is there a certain pattern or best practice here?

答案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"
英文:

You will need to define "doesn't really work". Other people see it working and don't understand.

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"

huangapple
  • 本文由 发表于 2023年6月8日 19:45:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76431531.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定