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