Comparing meta type when using if and switch

func foo<T>(caller: T.Type) {
    if caller == Int.self {
        print("it is Int - in if")
    }
    switch caller {
    case is Int.Type:
        print("it is Int - in switch")
    default: break
    }
}

return:

it is Int - in if
it is Int - in switch

why can't I use Int.self in switch's case?

You can, if you do case let caller where caller == Int.self, though personally I don't think it's an improvement.

I mean it doesn't make sense.

is is a type-casting pattern, which expects a metatype (.Type) and not a metatype instance (.self). So when you do case is that's what you need to provide. It's the same when you do something like caller is normally (i.e. outside of a switch context in this case), you need to provide a metatype i.e. caller is Int.Type. If you do caller is Int.self then you will get an error.

3 Likes