Switch on AnyClass type

From a playground:


if strClass == NSString.self {
  print("true")
}
switch strClass {
case is NSString:
  print(true)
default:
  print(false)
}


That's what I'd like to do. I have an object we pass along between platforms that encodes the class type and I'd like to have a switch statement on that class type. I could use if statements as they seem to work great, but I'd like the cleaner look of switch.

I dunno - given Swift, I'd think you'd want to stay w/if.

Accepted Answer

I'm not sure if your `if` testing works as expected.

func test1(strClass: AnyClass) {
    if strClass == NSString.self {
        print("true")
    }
}
test1(NSString.self) //->true
let nsStr: NSString = "string"
test1(nsStr.dynamicType) //(no output)


You can write an equivalent testing with `switch`, if you implement a matching operator for AnyClass.

func ~= (lhs: AnyClass, rhs: AnyClass) -> Bool {
    return lhs == rhs
}
func test2(strClass: AnyClass) {
    switch strClass {
    case NSString.self:
        print(true)
    default:
        print(false)
    }
}
test2(NSString.self) //->true
test2(nsStr.dynamicType) //->false


A little bit different type testing can be written with `switch` as follows:

func test3(strClass: AnyClass) {
    switch strClass {
    case is NSString.Type:
        print(true)
    default:
        print(false)
    }
}
test3(NSString.self) //->true
test3(nsStr.dynamicType) //->true
Switch on AnyClass type
 
 
Q