英文:
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"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论