Checking class type in switch in Swift: how to compare an instance with a type?
Hello everyone! I'm new to Swift and encountered a problem when working with classes and switch. I have a class hierarchy: a base class `Animal` and its subclasses `Dog`, `Cat`, `Bird`. I receive an array `[Animal]` and want to perform different actions for each element depending on its actual type. In Objective-C I could use `isKindOfClass:`, but in Swift this doesn't work.
Here's my current code that doesn't compile:
```swift
class Animal {}
class Dog: Animal {}
class Cat: Animal {}
class Bird: Animal {}
let animals: [Animal] = [Dog(), Cat(), Bird(), Dog()]
for animal in animals {
switch animal {
case is Dog:
print("Woof!")
case is Cat:
print("Meow!")
case is Bird:
print("Chirp!")
default:
print("Unknown an
No answers yet.
Log in to leave an answer