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?
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:
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With