I'm trying to switch on a type in swift. I'm not trying to switch on the type of an object instance, I'm trying to switch on the actual type itself. For example:
let t: Any.Type = Int.self
switch t {
case is Int:
print("int")
default:
print("other")
}
I would expect this to print "int" but it falls into the default case.
I can accomplish the desired result with an if statement, as in,
if t == Int.self
{
print("t is an int")
}
but I was hoping for a way to do this with a switch. I've read Apple's 'Type Casting' documentation, perhaps not thoroughly enough because I can't see a way to apply it here.
Xcode generates the following warning on the above case: "Cast from 'Any.Type' to unrelated Type 'Int' always fails" which hints at the correct way:
let t: Any.Type = Int.self
switch t {
case is Int.Type:
print("Int")
default:
print("Other")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With