2

I have done this:

func doSomething(anObject: AnyObject)
{
    switch anObject {
    case let myObj as MyClass:
        println("Is a kind of MyClass")
    case let yourObj as YourClass:
        println("Is a kind of YourClass")
    default:
        break
    }
}

Which works as you'd expect, classes and subclasses of MyClass or YourClass cause the relevant print statements to be executed.

However, I have a case where I want it to match an exact class (not any subclass of that class). Ideally I want something as simple and elegant as the case let myObj as MyClass: line, something like case let myObj as exactly MyClass:. Is something like this possible in Swift? Otherwise, what is the most elegant and concise way to achieve this within a case statement?

jhabbott
  • 18,461
  • 9
  • 58
  • 95
  • possible duplicate of [How do you find out the type of an object (in Swift)?](http://stackoverflow.com/questions/24101450/how-do-you-find-out-the-type-of-an-object-in-swift) – nhgrif Apr 19 '15 at 22:29

1 Answers1

2
class A {}
class B: A {}

let b = B()

let b_is_exactly_a = b.dynamicType === A.self // false
let b_is_exactly_b = b.dynamicType === B.self // true
let b_is_a = b is A // true
let b_is_b = b is B // true
zrzka
  • 20,249
  • 5
  • 47
  • 73