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

前端 未结 8 2019
臣服心动
臣服心动 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:33

    I think you are after a subclass of NSView. Try this:

    protocol TransmogrifiableView {
        func transmogrify()
    }
    
    class MyNSView: NSView, TransmogrifiableView {
        // do stuff.
    }
    

    And later in the code accept objects of type MyNSView.

    Edit

    You maybe want an Extension, see this

    extension NSView: TransmogrifiableView {
        // implementation of protocol requirements goes here
    }
    
    • Note that you will not be able to get an NSView without this extra method.
    • You can separately extend subclasses of NSView to override this new method.

    Yet another option is to make a class which holds a pointer to an NSView, and implements additional methods. This will also force you to proxy all methods from NSView that you want to use.

    class NSViewWrapper: TransmogrifiableView {
        var view : NSView!
        // init with the view required.
        //  implementation of protocol requirements goes here.
        .....
       // proxy all methods from NSView.
       func getSuperView(){
           return self.view.superView
       }
    }
    

    This is quite long and not nice, but will work. I would recommend you to use this only if you really cannot work with extensions (because you need NSViews without the extra method).

提交回复
热议问题