Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check two instances are the same class/type in swift

Tags:

swift

I know that I can check the type of a var in Swift with is

if item is Movie {     movieCount += 1 } else if item is Song {     songCount += 1 } 

but how can I check that two instances have the same class? The following does not work:

if item1 is item2.dynamicType {     print("Same subclass") } else {     print("Different subclass) } 

I could easily add a "class" function and update it in each subclass to return something unique, but that seems like a kludge...

like image 638
Grimxn Avatar asked Jun 11 '14 11:06

Grimxn


People also ask

What are instances in Swift?

Swift ObjectsAn object is called an instance of a class. For example, suppose Bike is a class then we can create objects like bike1 , bike2 , etc from the class. Here's the syntax to create an object. var objectName = ClassName()

What is a class in Swift?

Classes in Swift 4 are building blocks of flexible constructs. Similar to constants, variables and functions the user can define class properties and methods. Swift 4 provides us the functionality that while declaring classes the users need not create interfaces or implementation files.


1 Answers

I also answered How do you find out the type of an object (in Swift)? to point out that at some point Apple added support for the === operator to Swift Types, so the following will now work:

if item1.dynamicType === item2.dynamicType {     print("Same subclass") } else {     print("Different subclass") } 

This works even without importing Foundation, but note it will only work for classes, as structs have no dynamic type.

like image 135
Alex Pretzlav Avatar answered Sep 25 '22 22:09

Alex Pretzlav