Saturday, March 28, 2015

Swift Protocols and Generics

Airspeed Velocity:

So it looks like Printable is some kind of fixed-sized box that holds any kind of value that is printable. This kind of boxing is quite a common feature in other languages like Java and C#. But here even references to classes are put inside this 40-byte box, which might surprise you if you’re used to thinking of protocols as like refereces to pure virtual base classes. This Swift box is geared up to hold both value and reference types.

[…]

OK, so protocols used like this seem to add some level of indirection. Does that cost us anything compared to using the generic placeholder approach? To test this out, we can construct some trivial structs that perform a basic operation, and then attempt to run that operation multiple times via both a protocol and a generic placeholder.

[…]

Speaking of dynamic behaviour – that might be one occasion when you might prefer to use protocols rather than generics. […] A contrived example obviously, but it shows how even structs in Swift can get dynamic behaviour at runtime via protocols, that you might find a use-case for.

2 Comments RSS · Twitter

Ha, only when I read the pull quote on your post did I spot a typo in my article, oops!

[…] Previously: Swift Protocols, Arrays, and Casting, Swift Protocols Question, Swift Protocols and Generics. […]

Leave a Comment