How to check if an object is an instance of a certain type in Swift?
Hi! I started learning Swift and ran into a problem. I have a class hierarchy: a base class `Vehicle` and two subclasses `Car` and `Bicycle`. I create an array of type `[Vehicle]` containing different instances. Now I need to iterate through the array and perform different actions depending on the specific type of the object. For example, for `Car` print the number of doors, and for `Bicycle` print the number of gears.
In Objective-C I would use `isKindOfClass:`, but this doesn't work in Swift. I tried writing like this:
```swift
class Vehicle {
var name: String
init(name: String) {
self.name = name
}
}
class Car: Vehicle {
var doors: Int
init(name: String, doors: Int) {
self.doors = doors
super.init(name: name)
}
}
class Bicycle: Vehicl
No answers yet.
Log in to leave an answer