1

In this code:

protocol TestProtocol {
    var someVar: String { get }
}

protocol WithTestProtocol {
    var someVarWithTestProtocol: TestProtocol { get }
}

struct TestProtocolStruct: TestProtocol {
    var someVar: String {
        return ""
    }
}

struct WithTestProtocolStruct: WithTestProtocol {
    var someVarWithTestProtocol: TestProtocolStruct {
        return TestProtocolStruct()
    }
}

I get the error message:

Type 'WithTestProtocolStruct' does not conform to protocol 'WithTestProtocol'

Why is it not possible to conform to a protocol with a concrete implementation? Are there good workarounds?

I know, that this code works:

struct WithTestProtocolStruct: WithTestProtocol {
    var someVarWithTestProtocol: TestProtocol {
        return TestProtocolStruct()
    }
}

.. but I need to use a concrete implementation there because I want to use other stuff of the concrete implementation. I thought, it is a very common case and I`m wondering, why the compiler does not allow this.

tanaschita
  • 221
  • 4
  • 11
  • 1
    In `WithTestProtocol`, your `someVarWithTestProtocol` is of type `TestProtocol`, but in the implementation ( `WithTestProtocolStruct`) you're defining it as `TestProtocolStruct`. It should be `TestProtocol` too. – Alejandro Iván Aug 29 '18 at 13:37
  • Yes, I used a concrete implementation because a need the concrete implementation there. Because of the other stuff this implementation has. I thought, it is a really common case and that the compiler should be able to know that `TestProtocolStruct` conforms to `TestProtocol`. – tanaschita Aug 29 '18 at 13:53
  • 1
    @Hamish, thanks for the duplicate link, it answers the question. – tanaschita Aug 29 '18 at 14:01

2 Answers2

0

Your definition of protocol type is TestProtocol

struct WithTestProtocolStruct: WithTestProtocol {
    var someVarWithTestProtocol: TestProtocol {
        return TestProtocolStruct()
    }
}
Paul Peelen
  • 10,073
  • 15
  • 85
  • 168
Alex L
  • 309
  • 2
  • 9
0

You have to provide specific type while using protocol properties.

struct WithTestProtocolStruct: WithTestProtocol {
  var someVarWithTestProtocol: TestProtocol {
    return TestProtocolStruct()
  }
}

Practically TestProtocolStruct may or may not confirm the TestProtocol compiler won't allow this.

Prashant Tukadiya
  • 15,838
  • 4
  • 62
  • 98