2

I have two protocols:

protocol Test {
    func print()
}

protocol SpecifiedTest: Test {
    func printSomethingElse()
}

I want to have an interface for all objects that have the variable conforming to Test

protocol TestHolder {
    var test: Test! { get }
}

It works for all pure Test variables

class SuccessClass: TestHolder {
    var test: Test!
}

But when I try to use it with SpecifiedTest I get

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!

Any ideas why is that?

Is there any way to do this without generics?


Swift version 3.0.2 (swiftlang-800.0.63 clang-800.0.42.1), XCode Version 8.2.1 (8C1002)

shallowThought
  • 19,212
  • 9
  • 65
  • 112
shed
  • 121
  • 1
  • 8
  • Possible duplicate of [Protocol doesn't conform to itself?](http://stackoverflow.com/questions/33112559/protocol-doesnt-conform-to-itself). – Martin R Jan 12 '17 at 18:35
  • What happens if someone takes an instance `fc` of `FailureClass`, treats it as a `TestHolder`, assigns something to `test` of type `Test` - what value does the `test` variable of the instance `fc` hold? It surely cannot be what you just assigned because there is no guarantee it is a `SpecifiedTest`... – luk2302 Jan 12 '17 at 18:37
  • @luk2302 TestHolder specify only getter, there is no way to assign pure Test. I understand this restrictions for setter. But basically I just want to say "You can have Test from this class". Btw it's work well if in protocol I require `func getTest() -> Test` instead variable. But in that way I need to implement this function in every instance class. And what's a difference anyway? Isn't variables semantically just a pair of getter and setter functions? What's a problem to allow this for geters. – shed Jan 12 '17 at 19:00

0 Answers0