Checking type equivalence properly

what check on variable type would be equivalent to val is T?

protocol P {}
struct S: P {}

func foo<T, R>(_ val: T, _ type: R.Type) {
    let a = val is R
    let b = T.self == type // FIXME. smth like <= ?
    assert(a == b)
}

foo(0, Int.self) // ok
foo([0], [Int].self) // ok

foo(0, Any.self) // assert fails
foo([0], [Any].self) // assert fails

foo(S(), P.self) // assert fails
foo([S()], [P].self) // assert fails

print("done")

There is no equivalent. is performs the same kind of check as as?, which means it has to know all possible checked run-time conversions. There’s no way to get that effect manually, at least not on arbitrary types.

1 Like

Up to mid-last year,

T.self is R.Type

would have returned true where you're seeing false. It's a bug, and it broke some useful code of mine. :pouting_cat:

1 Like
Terms of Service

Privacy Policy

Cookie Policy