Skip to content

Instantly share code, notes, and snippets.

@dataxpress
Created September 2, 2014 16:00
Show Gist options
  • Save dataxpress/785bf406ad0f16b9400e to your computer and use it in GitHub Desktop.
Save dataxpress/785bf406ad0f16b9400e to your computer and use it in GitHub Desktop.
Switching on type of object in Swift
// Playground - noun: a place where people can play
class Abc
{
}
class Def
{
}
// declaring as AnyObject here is important - swich statement gets mad otherwise
let something : AnyObject = Abc()
switch something {
case let something as Abc:
println("It's an Abc.")
break;
case let something as Def:
println("It's a Def.")
break;
default:
println("It's something else.")
}
// maybe not as useful but if you only want to know the type and don't need to cast it for whatever reason you can also just provide `let _`:
switch something {
case let _ as Abc:
println("It's an Abc.")
break;
case let _ as Def:
println("It's a Def.")
break;
default:
println("It's something else.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment