Understanding the "cast from 'any P' to unrelated type 'S' always fails" warning

i wrote some code like the following:

public
struct S
{
}

public
func f(values:[any Identifiable<Int>])
{
    for case let value as S in values
    {
    }
}

my intention was to retroactively conform S to Identifiable<Int> in a downstream module. the goal was to have f be able to discover an instance of S only if the app includes a conformance of S to Identifiable<Int>.

but instead, i get this warning:

warning: cast from 'any Identifiable<Int>' to unrelated type 'S' always fails
    for case let value as S in values

is this something that is supported by the type system?

2 Likes

I believe the warning is a bit of lie—if you do provide that retroactive conformance then the cast will, in fact, succeed. Perhaps we ought to allow silencing this warning somehow when that's the author's intention, maybe by module-qualifying the types involved, as one can do to silence the retroactive conformance warning?

2 Likes

Having some explicit indicator that you really mean to do this would also be a good way to prevent the optimiser from eliminating the actual runtime check. Otherwise, I wouldn't trust future compiler versions to not optimise this out, irrespective of what the current version happens to do.