11

The keyword is is equivalent to isKindOfClass.

But I am unable to find what is equivalent of isMemberOfClass in swift.

Note: My question is not about the difference between isKindOfClass or isMemberofclass rather the question is about what is the equivalent of isMemberofClass in Swift

somebody please clarify

RajuBhai Rocker
  • 723
  • 1
  • 7
  • 24

2 Answers2

19

You are looking for type(of:) (previously .dynamicType in Swift 2).

Example:

class Animal {}
class Dog : Animal {}
class Cat : Animal {}

let c = Cat()

c is Dog // false
c is Cat // true
c is Animal // true

// In Swift 3:
type(of: c) == Cat.self // true
type(of: c) == Animal.self // false

// In Swift 2:
c.dynamicType == Cat.self // true
c.dynamicType == Animal.self // false
Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
Grimxn
  • 22,115
  • 10
  • 72
  • 85
2

In case of optional variable type(of:) returns the type from initialization.

Example:

class Animal {}
class Cat : Animal {}

var c: Animal?
c = Cat()

type(of: c) // _expr_63.Animal>.Type
type(of: c) == Cat?.self // false
type(of: c) == Animal?.self // true

My class was inherited from NSObject, so I used its variable classForCoder and it worked for me.

class Animal : NSObject {}
class Cat : Animal {}

var c: Animal?
c = Cat()
c?.classForCoder == Cat.self // true