Existential types let you work with values of any type that follow a certain rule or protocol. The any keyword makes it clear you want to use a value that can be any type matching that rule.
Existential types (any keyword) in Swift
let variableName: any ProtocolNameThe any keyword explicitly marks a type as existential, meaning it can hold any value conforming to the protocol.
Before Swift 5.7, existential types were implicit, but now any is required for clarity.
shape that can hold any value that follows the Drawable protocol.protocol Drawable { func draw() } let shape: any Drawable
any keyword to mark the parameter type.func printDescription(_ item: any CustomStringConvertible) { print(item.description) }
Equatable, using any to allow mixed types.var items: [any Equatable] = [5, "hello", 3.14]
This program defines a protocol Greetable and two types that follow it: Person and Robot. The function sayHello takes any Greetable value using the any keyword and calls its greet() method. It then prints greetings from both a person and a robot.
protocol Greetable { func greet() -> String } struct Person: Greetable { var name: String func greet() -> String { return "Hello, \(name)!" } } struct Robot: Greetable { func greet() -> String { return "Beep boop." } } func sayHello(to entity: any Greetable) { print(entity.greet()) } let alice = Person(name: "Alice") let bot = Robot() sayHello(to: alice) sayHello(to: bot)
Using any makes your code clearer about when you are working with existential types.
Existential types can have some performance cost compared to concrete types because Swift uses dynamic dispatch.
You cannot use protocol methods that require Self or associated types directly with existential types without extra work.
any marks a type as existential, meaning it can hold any value conforming to a protocol.
Use existential types to write flexible code that works with many types sharing behavior.
Existential types improve code clarity and safety by making type flexibility explicit.