0
0
Swiftprogramming~7 mins

Existential types (any keyword) in Swift

Choose your learning style9 modes available
Introduction

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.

When you want to store different types that share the same behavior in one place.
When you want to pass a value to a function but don't care about its exact type, only that it follows a protocol.
When you want to write flexible code that works with many types without knowing them all in advance.
Syntax
Swift
let variableName: any ProtocolName

The 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.

Examples
This declares a variable shape that can hold any value that follows the Drawable protocol.
Swift
protocol Drawable {
    func draw()
}

let shape: any Drawable
This function accepts any value that can describe itself as a string, using the any keyword to mark the parameter type.
Swift
func printDescription(_ item: any CustomStringConvertible) {
    print(item.description)
}
An array holding different types that all conform to Equatable, using any to allow mixed types.
Swift
var items: [any Equatable] = [5, "hello", 3.14]
Sample Program

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.

Swift
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)
OutputSuccess
Important Notes

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.

Summary

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.