Avatar ·

How to determine the type of an object in Swift? (type(of:) and is/as)

Hi everyone! I just started learning Swift and am writing my first app. I ran into a problem: I need to understand what type of object is stored in a variable, especially when I use protocols or inheritance. Here's an example. I have a base class `Animal` and two subclasses: `Dog` and `Cat`. I create an array `let animals: [Animal] = [Dog(), Cat(), Dog()]` and want to determine in a for-in loop which ones are dogs and which are cats. In other languages (e.g., C#), I used `typeof()` or `is` for checking. How do I do this in Swift? I tried writing `if animal is Dog { ... }`, but this only works for checking, not for getting the type name as a string. I also heard about `type(of:)`, but I don't understand the difference between `type(of:)` and `is`/`as`. I need not just to check, but sometimes to cast the object.