Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIView isKindOfClass in Swift 3

So I have this code:

if view.isKindOfClass(classType){...}

This worked fine in Swift 2, but now that I'm in Swift 3, I get this error:

Value of type UIView has no member isKindOfClass

How do I test this in Swift 3?

like image 591
Steven Jacks Avatar asked Oct 01 '16 11:10

Steven Jacks


3 Answers

You can try with these three options in Swift 3:

Option 1:

if view is UITabBarItem {

}

Option 2:

if view.isKind(of:UITabBarItem.self) {

}

Option 3:

if view.isMember(of:UITabBarItem.self) {

}

The difference between isKind:of and isMember:of is:

  • isKind:of returns YES if the receiver is an instance of the exact class, OR if the receiver is an instance of any subclass of the class.
  • isMember:of only returns YES if the receiver is an instance of the exact class you're checking against
like image 147
Marlon Ruiz Avatar answered Oct 26 '22 17:10

Marlon Ruiz


You can use isKind(of:) but it's better to use the more swifty is and as:

See a dumb example:

import Foundation

class Base {}
class SuperX: Base {}
class X: SuperX {}
class Y {}

func f(p: Any) {
    print("p: \(p)")
    guard let x = p as? Base
        else { return print("    Unacceptable") }

    if x is X {
        print("    X")
    }
    if x is SuperX {
        print("    Super X")
    }
    else {
        print("    Not X")
    }
}

f(p: Base())
f(p: SuperX())
f(p: X())
f(p: "hey")
f(p: Y())
f(p: 7)

Run the code in a playground an the output will be:

p: Base
    Not X
p: SuperX
    Super X
p: X
    X
    Super X
p: hey
    Unacceptable
p: Y
    Unacceptable
p: 7
    Unacceptable
like image 29
djromero Avatar answered Oct 26 '22 17:10

djromero


Just use is operator for checking like

if view is UITableViewCell { 
  //do something
}

or

guard view is UITableViewCell else {
  return
}
//do something

if you need to use the view as instance of class type use as operator for casting:

if let view = view as? UITableViewCell {
  //here view is a UITableViewCell
}

or

guard let view = view as? UITableViewCell else {
  return
}
//here view is a UITableViewCell
like image 29
Giuseppe Travasoni Avatar answered Oct 26 '22 17:10

Giuseppe Travasoni