Using non-escaping closures in methods satisfying a protocol method with an escaping closure

Looking at the Protocol Witness Matching mini-manifesto, we can implement a protocol's throwing method with a never-throwing method, or a fail-able initializer with a never-fail initializer. But it also let us implement a method with a parameter that is an escaping closure with a method that takes a non-escaping closure as a parameter. I would think it should be the other way around. Does anyone understand the sub-typing theory here?

1 Like

I would think it should be the other way around

Hmm, why do you think so?

Function parameters are contravariant, because when an instance of the subtype is stored as the supertype, anything the supertype’s function accepts could be passed into the subtype’s function.

In that scenario here, code which is generic over the protocol (or uses an existential) could pass an @escaping closure to an instance of a conforming type whose method is declared as accepting a non-escaping closure.

And that’s not actually a problem, because an escaping closure can certainly be used in a non-escaping manner.

On the other hand, it would be a problem if the protocol specified a non-escaping parameter, but the conforming type tried to make it @escaping.

Essentially, @escaping is a subtype of non-escaping.

4 Likes