[英]How can I test if an instance is a specific class or type in Swift?
Objective-C has two methods to test if an object is an instance of a specific class or a subclass: Objective-C有两种方法来测试对象是否是特定类或子类的实例:
- (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: 在Swift中,我可以使用
is
运算符测试后者:
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)? 如何测试实例是否是Swift中的特定类或类型(即使在处理没有NSObject子类时)?
Note: I'm aware of func object_getClassName(obj: AnyObject!) -> UnsafePointer<Int8>
. 注意:我知道
func object_getClassName(obj: AnyObject!) -> UnsafePointer<Int8>
。
请参阅我的答案(可能重复) https://stackoverflow.com/a/26365978/195691 :现在可以比较Swift中动态类型的标识:
myVariable.dynamicType === MyClass.self
Swift 3+ we can do this using type(of: T) function. Swift 3+我们可以使用type(of:T)函数来做到这一点。
let view = UIView()
if type(of: view) == UIView.self {
print("view isMember of UIView")
}
In addition to object_getClassName()
, invariants can be maintained by using a definitional equality in conjunction with object_getClass()
除了
object_getClassName()
,还可以通过结合object_getClass()
使用定义相等来维护不变量。
object_getClass(X()) === object_getClass(X()) // true
object_getClass(X()) === object_getClass(Y()) // false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.