简体   繁体   English

如何测试实例是否是Swift中的特定类或类型?

[英]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.

相关问题 我可以声明一个符合Swift协议的特定类的类型吗? - Can I declare a type that is a specific class conforming to a protocol in Swift? 如何在Swift中检查实例的类型? - How can I check an instance's type in Swift? 如何判断Swift中实例变量的类是什么 - How can I tell what the class of an instance variable is in Swift 如何将NSMutableArray转换为特定类型的Swift数组? - How can I cast an NSMutableArray to a Swift array of a specific type? 如何在Swift中为特定类型的数组进行扩展 - How can I make a extension for array of specific type in Swift 如何快速使用ccPhysicsCollisionBegin查找特定类型的对象与另一个对象的单个实例之间的冲突? - How do I, in swift, use ccPhysicsCollisionBegin to find the collision between a specific type of object and a singular instance of another object? 如何在 Swift 中动态地将项目添加到 class 类型的数组中 - How can I add Items to an array of a class type, dynamically in Swift 如何在Swift中访问类的实例 - How do I access an instance of a class in Swift 斯威夫特:如果我在变量中有实例的名称,如何创建类的实例? - Swift: How to create instance of a class, if I have the name of the instance in a variable? Swift - 具有特定类类型的数组 - Swift - Array with specific class type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM