子协议变量不符合父协议

时间:2017-01-12 18:33:26

标签: swift swift3 protocols

我有两个协议:

protocol Test {
    func print()
}

protocol SpecifiedTest: Test {
    func printSomethingElse()
}

我希望为所有变量符合Test

的变量的对象提供接口
protocol TestHolder {
    var test: Test! { get }
}

适用于所有纯Test变量

class SuccessClass: TestHolder {
    var test: Test!
}

但是当我尝试将其与SpecifiedTest一起使用时,我得到了

class FailureClass: TestHolder {
    var test: SpecifiedTest!
}

Playground execution failed: error: MyPlayground.playground:13:11: error: type 'FailureClass' does not conform to protocol 'TestHolder'
    class FailureClass: TestHolder {
          ^

MyPlayground.playground:2:13: note: protocol requires property 'test' with type 'Test!'; do you want to add a stub?
        var test: Test! { get }
            ^

MyPlayground.playground:14:13: note: candidate has non-matching type 'SpecifiedTest!'
        var test: SpecifiedTest!

任何想法为什么会这样?

如果没有泛型,有没有办法做到这一点?

Swift 3.0.2版(swiftlang-800.0.63 clang-800.0.42.1),XCode版本8.2.1(8C1002)

0 个答案:

没有答案