What if you could treat many different things the same way without writing extra code for each?
Why Existential types (any keyword) in Swift? - Purpose & Use Cases
Imagine you want to store different types of shapes like circles, squares, and triangles in one box. Each shape has its own way to draw itself. Without a common way to treat them, you must write separate code for each shape type.
Manually handling each shape type means writing repetitive code and checking types everywhere. This slows you down and makes your code messy and hard to fix when you add new shapes.
The any keyword lets you say: "I want a box that can hold any shape that follows the drawing rules." This way, you treat all shapes the same, no matter their specific type, making your code cleaner and easier to manage.
var shapes: [Circle | Square | Triangle] = [...] for shape in shapes { if let circle = shape as? Circle { circle.draw() } else if let square = shape as? Square { square.draw() } else if let triangle = shape as? Triangle { triangle.draw() } }
var shapes: [any Drawable] = [...] for shape in shapes { shape.draw() }
You can write flexible code that works with any type following a rule, making your programs easier to grow and maintain.
Think of a music app that plays different audio formats. Using any, it can treat all audio files the same way without knowing their exact format upfront.
Manual type checks make code complex and error-prone.
any groups different types under one common behavior.
This leads to simpler, more flexible, and maintainable code.