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

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

    As per definition a protocol just declares requirements of "methods, properties an other requirements". And by "other requirements" it means a superclass is not a part of it.

    A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.

    Right now, I don't see a clean solution. It's possible to use a where-clause to define a type which is a NSView and conforms to the TransmogrifiableView like this:

    class MyClass {
        var aTransmogrifiableNSView: T
    }
    

    Or you could use another superclass:

    protocol TransmogrifiableViewProtocol {
        func transmogrify()
    }
    
    class TransmogrifiableView: NSView, TransmogrifiableViewProtocol {
        func transmogrify() {
            assert(false, "transmogrify() must be overwritten!")
        }
    }
    
    class AnImplementedTransmogrifiableView: TransmogrifiableView {
        func transmogrify() {
            println("Do the transmogrification...")
        }
    }
    

    In the end both solutions aren't clean and wouldn't satisfy myself. Maybe an abstract-keyword will be added to Swift someday?

提交回复
热议问题