[swift-evolution] [Pitch] CRTP in Swift

Adrian Zubarev adrian.zubarev at devandartist.com
Thu Feb 23 12:54:23 CST 2017


First of all, writing CRTP is already allowed in Swift, however it doesn’t work at all.

For example one would assume that the output of the following code sample might look like this 1 2 3 4:

print(1)

class Template<T> {}

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

let instance = RealThing()
instance.foo()

print(4)
However the result is only 1 and your application will simply stuck at that point without crashing or throwing any bad runtime error.

https://bugs.swift.org/browse/SR–2549

I discovered an API in UIKit which uses that pattern, obviously it’s written in Objective-C but it is imported in Swift and it actually works, because it’s not pure swift.

// 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> { ... }
My questions are:

Will we ever allow this in Swift?
Does CRTP bring any technical improvement to Swifts generic system?
Is it something for Swift 4 to consider?
Does it need a proposal or should we only see it as a bug?


-- 
Adrian Zubarev
Sent with Airmail
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20170223/74a8ef05/attachment.html>


More information about the swift-evolution mailing list