Dynamic dispatch in struct && protocol

protocol Drawable {
    func draw()
}

struct Point: Drawable {
    func draw() {
        //
    }
}
struct Line: Drawable {
    func draw() {
        //
    }
}
let drawable: [Drawable]
drawable.forEach { $0.draw() }

in this case, Is there a dynamic dispatch? even if struct?

Yes. Instances of protocol types, such as Drawable, are stored not as Point or Line themselves, but as existential containers that have pointers to tables with conforming methods. Because it is not known which of the Drawables are stored in the array, the code will go through these tables to find the exact implementation that needs to be called.

2 Likes

In particular, all and only protocol requirements and class members use dynamic dispatch (there's also Obj-C message-sending system, but heck).

Now, there is one caveat due to how Swift compiles generics: all generics use the same function for protocol requirement.

Let's say, you add another generic shape.

struct X<Value> { ... }

All instances of X, regardless of the type of Value, will use the same function when referring to Drawable.draw.

2 Likes
Terms of Service

Privacy Policy

Cookie Policy