Have you ever discovered CRTP (Curiously recurring template pattern)?

In iOS 9 the UIKit team changed the way NSLayoutAnchor API is implemented to CRTP.

// Generic superclass
open class NSLayoutAnchor<AnchorType : AnyObject> : NSObject { ... }

// Non-generic subclasses with the `Sub : Super<Sub>` pattern
open class NSLayoutXAxisAnchor : NSLayoutAnchor<NSLayoutXAxisAnchor> {}
open class NSLayoutYAxisAnchor : NSLayoutAnchor<NSLayoutYAxisAnchor> {}
open class NSLayoutDimension : NSLayoutAnchor<NSLayoutDimension> { ... }

The actual API is implemented in Objective-C, but is easily bridged to Swift, which raises the following question in my mind: Can we use the same pattern in Swift?

The answer is yes and no! It’s totally fine to design some Swift template and use it the CRTP way.

class Template<T> {
    // Implement something really special using `T` here

class RealThing : Template<RealThing> {
    // `RealThing` will now inherit your special art from the template
    // and it will be of type `RealThing`, which is awesome

But lets try out the pattern in playground and see how it truly behaves.


class Template<T> {}

class RealThing : Template<RealThing> {
    override init() { print(2) }
    func foo() { print(3) }

let instance = RealThing()


The expected result would look like 1 2 3 4, but the reality is just a single 1. CRTP in Swift locks on the initializer execution. The good thing about this is, there are no errors thrown during runtime. :)

This is clearly a bug: SR-2549