Home > front end >  Swift which method dispatch is used?
Swift which method dispatch is used?

Time:06-18

Which dispatch method is used in the following example. I read through some articles and seems to be any extensions methods are static. But is it calls witness table.

My assumptions is that static dispatch uses only single declarations of methods, but there are two implementations.

Unfortunately i can't check the SIL by myself right now(

protocol BBBB {
    func printSome()
}

extension BBBB {
    func printSome() {
        print("A")
    }
}

class AAA { }

extension AAA: BBBB {
    func printSome() {
        print("B")
    }
}

let aaaa = AAA()
aaaa.printSome()

Feel free to discuss :)

CodePudding user response:

This method can be statically dispatched, because aaaa has one fixed, statically-known type (AAA).

If you instead had something like anyBBBB: any BBBB = aaa, then calling anyBBBB.printSome() would need dynamic dispatch, because it's not known which concrete type is involved until runtime. (Of course, if the compiler's data-flow analysis can prove there's only one possible type in that spot, then it can switch back to static dispatch. This is called Devirtualization)

  • Related