Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch on Any.Type

Tags:

swift

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.

like image 684
Philip Avatar asked Dec 19 '22 18:12

Philip


1 Answers

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")
 }
like image 116
Philip Avatar answered Jan 18 '23 21:01

Philip