简体   繁体   中英

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:

- (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:

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)?

Note: I'm aware of 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.

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_getClass(X()) === object_getClass(X()) // true
object_getClass(X()) === object_getClass(Y()) // false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM