Advanced Swift: Generics and Protocols · Generic Constraints | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/1940187-advanced-swift-generics-and-protocols/lessons/3

Doesn’t Swift compiler inline + function in compile time automatically if it’s possible? Do we have to use the keyword @inlinable explicitly to make the + function inlined in our method block?

Good point! Yes it does if it is within the module and you are using whole module optimization. If you are outside the module it will hide the implementation. If you want to build a framework that can ship separately, and performance is critical, you will want to use the @inlinable attribute.

This might be interesting to you for more background:

1 Like

What is a “witness table”. I heard you mention it around 2:04.
“It can use this witness table to call the plus operation.”

Great question. There was some last minute reorganization and this explanation sort of got lost. You can check out the protocol oriented program course for some info on witness tables but let me go ahead and explain it here. You might be familiar with virtual tables for classes. These are like a table of function pointers that get passed around with an object. This virtual table is used to call the right overridden method for an object. When you create a protocol, a “witness table” is created which has the functions for the conforming type. When you pass a type with a constraint, the “witness” for this constraint is passed behind the scenes. Each constraint corresponds to a behind the scenes witness table being passed so that the compiler can write a version of the function that knows nothing about the type. The compiler can also write specialized versions that don’t use witness table dispatch but statically bake in the call for speed.

1 Like