Search code examples
swiftswift-protocols

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


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 realized that using as? could work, but is there a certain pattern or best practice here?


Solution

  • 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"