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

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

    For Swift 4, based on @Antoine's keen insight:

    Create a protocol then use a typealias to give a cleaner name to a type that conforms to both a class and the protocol.

    protocol Transmogrifiable {
        func transmogrify()
    }
    typealias TransmogrifiableView = NSView & Transmogrifiable
    

    You can then define a class that inherits from that type....

    class ATransmogView: TransmogrifiableView {
        func transmogrify() {
            print("I'm transmogging")
        }
    }
    

    ....or define a class that inherits from the protocol and a subclass

    // this also qualifies as a TransmogrifiableView
    
    class BTransmogView: NSTextView, Transmogrifiable {
        func transmogrify() {
            print("I'm transmogging too")
        }
    }
    

    Now you can do this.

    func getTransmogrifiableView() -> TransmogrifiableView {
        return someBool ? ATransmogView() : BTransmogView()
    }
    

    And this now compiles.

    let myView: TransmogrifiableView = getTransmogrifiableView()
    let theSuperView = myView.superView
    

提交回复
热议问题