Swift — Require classes implementing protocol to be subclasses of a certain class

Update. In the latest Swift version you can just write

protocol TransmogrifiableView: NSView {
    func transmogrify()
}

, and this will enforce the conformer types to be either NSView, or a subclass of it. This means the compiler will “see” all members of NSView.


Original answer

There is a workaround by using associated types to enforce the subclass:

protocol TransmogrifiableView {
    associatedtype View: NSView = Self
    func transmogrify()
}

class MyView: NSView, TransmogrifiableView { ... } // compiles
class MyOtherClass: TransmogrifiableView { ... } // doesn't compile

Leave a Comment