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?

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