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

前端 未结 8 1978
臣服心动
臣服心动 2021-01-01 08:58

I\'m creating several NSView classes, all of which support a special operation, which we\'ll call transmogrify. At first glance, this seems like t

相关标签:
8条回答
  • 2021-01-01 09:37

    check this solution here... Swift - class method which must be overridden by subclass

    This solution allows to inherit from a class and also to have the protocol's compile time check. :)

    0 讨论(0)
  • 2021-01-01 09:39

    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
    
    0 讨论(0)
提交回复
热议问题