所以我有这段代码:
if view.isKindOfClass(classType){...}
这在Swift 2中运行良好,但是现在我在Swift 3中,我收到了这个错误:
UIView
类型的值没有成员isKindOfClass
如何在Swift 3中测试?
答案 0 :(得分:35)
您可以在 Swift 3 :
中尝试这三个选项选项1:
if view is UITabBarItem {
}
选项2:
if view.isKind(of:UITabBarItem.self) {
}
选项3:
if view.isMember(of:UITabBarItem.self) {
}
isKind:of和isMember:of is:
之间的区别答案 1 :(得分:6)
您可以使用isKind(of:)
,但最好使用更加敏捷的is
和as
:
看一个愚蠢的例子:
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)
在游乐场中运行代码,输出将为:
p: Base
Not X
p: SuperX
Super X
p: X
X
Super X
p: hey
Unacceptable
p: Y
Unacceptable
p: 7
Unacceptable
答案 2 :(得分:0)
快速类型转换
退休金
class MediaItem {}
class Movie: MediaItem {}
class Song: MediaItem {}
var mediaItem = MediaItem()
let movie = Movie()
let song = Song()
is
-运算符用于检查(返回true或false)实例的类型。
is
替换为isKind(of:)
的{{1}}。 isKindOfClass
适用于Swift中的任何类,而is
仅适用于isKind(of:)
的子类或以其他方式实现NSObject
(so answer)
NSObjectProtocol
if mediaItem is MediaItem { //true
print("mediaItem is MediaItem:\(mediaItem)") //mediaItem is MediaItem:MediaItem
}
if movie is Movie { //true
print("movie is Movie:\(movie)") //movie is Movie:Movie
}
if movie is MediaItem { //true
print("movie is MediaItem:\(movie)") //movie is MediaItem:Movie
}
if song is Movie { //false
print("song is Movie:\(song)") //IS NOT CALLED
}
-运算符用于将实例投射到另一种类型。
某个类类型的常量或变量实际上可能是指幕后子类的实例。如果您认为是这种情况,可以尝试使用类型转换运算符(as
或as?
)向下转换到子类类型。
as!
要找出类型,请使用if let mediaItem = mediaItem as? MediaItem { //success
print("mediaItem as MediaItem:\(mediaItem)") //mediaItem as MediaItem:MediaItem
}
if let movie = movie as? Movie { //success
print("movie as Movie:\(movie)") //movie as Movie:Movie
}
if let mediaItem = movie as? MediaItem { //success
print("movie as MediaItem:\(mediaItem)") //movie as MediaItem:Movie
}
if let song = song as? Movie { //failed
print("song as Movie:\(song)") //IS NOT CALLED
}
方法
type(of:)
了解更多here
答案 3 :(得分:0)
只需使用is
运算符进行检查
if view is UITableViewCell {
//do something
}
或
guard view is UITableViewCell else {
return
}
//do something
如果您需要使用视图作为类类型的实例,请使用as
运算符进行转换:
if let view = view as? UITableViewCell {
//here view is a UITableViewCell
}
或
guard let view = view as? UITableViewCell else {
return
}
//here view is a UITableViewCell