Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test if an instance is a specific class or type in Swift?

Tags:

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>.

like image 746
Klaas Avatar asked Aug 24 '14 22:08

Klaas


People also ask

What is an instance of a type Swift?

Instance methods are functions that belong to instances of a particular class, structure, or enumeration. They support the functionality of those instances, either by providing ways to access and modify instance properties, or by providing functionality related to the instance's purpose.

How do you check if an object is a specific type?

You can check object type in Java by using the instanceof keyword. Determining object type is important if you're processing a collection such as an array that contains more than one type of object. For example, you might have an array with string and integer representations of numbers.

Is type of class Swift?

Type classes, also known as extension interfaces, are usually represented in Swift as protocols with associated types and/or Self requirements. They are groups of functions that operate on generic type parameters and are governed by algebraic laws.


1 Answers

See my answer at (possible duplicate) https://stackoverflow.com/a/26365978/195691: It's now possible to compare identity of dynamic types in Swift:

myVariable.dynamicType === MyClass.self
like image 141
Alex Pretzlav Avatar answered Sep 26 '22 19:09

Alex Pretzlav