7

Objective-C has two methods to test if an object is an instance of a specific class or a subclass:

- (BOOL)isMemberOfClass:(Class)aClass;

Returns a Boolean value that indicates whether the receiver is an instance of a given class.

- (BOOL)isKindOfClass:(Class)aClass;

Returns a Boolean value that indicates whether the receiver is an instance of given class or an instance of any class that inherits from that class.

In Swift I can test for the latter by using the is operator:

if myVariable is UIView {
    println( "I'm a UIView!")
}

if myVariable is MyClass {
    println( "I'm a MyClass" )
}

How can I test if an instance is a specific class or type in Swift (even when dealing with no NSObject subclasses)?

Note: I'm aware of func object_getClassName(obj: AnyObject!) -> UnsafePointer<Int8>.

Klaas
  • 22,394
  • 11
  • 96
  • 107
  • `if myVariable is UIView ` doesn't need myVarible to be an instance of NSObject subclass. – Kreiri Aug 24 '14 at 22:35
  • @Kreiri Yes, but I'm looking for a solution that works with any kind of classes. UIView is just an example that is testable with `isKindOfClass`. Added another more generic example. – Klaas Aug 24 '14 at 23:01
  • 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) – Alex Pretzlav Oct 14 '14 at 17:03

3 Answers3

7

See my answer at (possible duplicate) https://stackoverflow.com/a/26365978/195691: It's now possible to compare identity of dynamic types in Swift:

myVariable.dynamicType === MyClass.self
Community
  • 1
  • 1
Alex Pretzlav
  • 15,505
  • 9
  • 57
  • 55
6

Swift 3+ we can do this using type(of: T) function.

let view = UIView()
if type(of: view) == UIView.self {
    print("view isMember of UIView")
}
Hari Kunwar
  • 1,661
  • 14
  • 10
0

In addition to object_getClassName(), invariants can be maintained by using a definitional equality in conjunction with object_getClass()

object_getClass(X()) === object_getClass(X()) // true
object_getClass(X()) === object_getClass(Y()) // false
CodaFi
  • 43,043
  • 8
  • 107
  • 153