Wak
Wak

Reputation: 878

Swift compiler can't check for protocol type

On the following code:

protocol BananaProtocol {
    var banana: Bool { get}
}

class MyBanana: BananaProtocol {
    var banana = true
}

protocol BananaProvider {
    var provider: BananaProtocol { get }
}

class BananaProviderImpl: BananaProvider {
    var provider = MyBanana()
}

The compiler complains with the error: Type 'BananaProviderImpl' does not conform to protocol 'BananaProvider'

If I change to:

class BananaProviderImpl: BananaProvider {
    var provider = MyBanana() as BananaProtocol
}

It works.

Why can't the compiler infer that MyBanana is of type BananaProtocol since it's on the class signature? class MyBanana: BananaProtocol

I'd appreciate some help understanding this issue. Thanks.

Upvotes: 0

Views: 78

Answers (1)

user652038
user652038

Reputation:

A type that adopts a protocol is not the same thing as the protocol existential. (e.g. MyBanana is not BananaProtocol.)

Recommendation: never use existentials.

protocol BananaProvider {
  associatedtype Banana: BananaProtocol
  var provider: Banana { get }
}

class BananaProviderImpl: BananaProvider {
  var provider = MyBanana()
}

Upvotes: 1

Related Questions