Coercing `any` into `some`

In this fragment I am getting an error:

protocol P: Equatable {}
struct S: P {}
func foo(_ value: some P) {}
let a: Any = S()

foo(a as! any P) // ❌ Type 'any P' cannot conform to 'P'

I suppose it is expected behaviour.

However this compiles fine:

foo((a as! any P)) // ✅

Ditto this:

let p: any P = a as! any P
foo(p) // ✅

Was this done on purpose to be able to silence the error?

3 Likes

i'm not 100% sure if this explains everything, but it looks like this scenario may be covered in this section of the implicit open existentials evolution doc. seems like the as any P type casts will suppress implicit opening of existentials, which is presumably why you get the self-conformance error in this case. parenthesizing the cast disables that suppression mechanism so you get back the implicit opening behavior.

7 Likes