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>
.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With