Created
September 2, 2014 16:00
-
-
Save dataxpress/785bf406ad0f16b9400e to your computer and use it in GitHub Desktop.
Switching on type of object in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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