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.
Practice
any keyword indicate in Swift when used with a protocol type?Solution
Step 1: Understand the role of
Theanyin Swiftanykeyword is used to mark a type as existential, meaning it can hold any value that conforms to a given protocol.Step 2: Compare with other options
The incorrect options describe behaviors unrelated toany. It does not create new protocols, restrict to one type, or convert protocols to classes.Final Answer:
It marks the type as existential, allowing any value conforming to the protocol. -> Option BQuick Check:
anymeans existential type [OK]
any means 'any conforming type' [OK]- Thinking
anycreates a new protocol - Confusing
anywith type restriction - Assuming
anyconverts protocols to classes
Drawable using existential types?Solution
Step 1: Recall the syntax for existential types
In Swift, to declare a variable that can hold any value conforming to a protocol, you useany ProtocolName. So here, it isany Drawable.Step 2: Analyze each option
var shape: Drawable missesany, so it is not explicit existential. var shape: Drawable & any and var shape: Drawable<any> have incorrect syntax. Only var shape: any Drawable uses the correct syntax.Final Answer:
var shape: any Drawable -> Option CQuick Check:
Existential syntax =any Protocol[OK]
any before protocol name for existential types [OK]- Omitting
anykeyword - Placing
anyafter protocol name - Using angle brackets incorrectly
protocol Greetable {
func greet() -> String
}
struct Person: Greetable {
func greet() -> String { "Hello" }
}
let greeter: any Greetable = Person()
print(greeter.greet())Solution
Step 1: Understand the protocol and struct
The protocolGreetablerequires agreet()method returning a String. The structPersonimplements this method returning "Hello".Step 2: Analyze the existential usage and output
The variablegreeteris declared asany Greetableand assigned aPersoninstance. Callinggreeter.greet()calls the implemented method and returns "Hello".Final Answer:
Hello -> Option AQuick Check:
Existential calls implemented method = "Hello" [OK]
- Expecting a compile or runtime error
- Thinking protocol methods are not accessible
- Assuming nil is returned
protocol Runnable {
func run()
}
struct Dog: Runnable {
func run() { print("Dog runs") }
}
var runner: Runnable = Dog()
runner.run()Solution
Step 1: Check variable declaration syntax
Since Swift 5.7, existential types require theanykeyword explicitly. The declarationvar runner: Runnableis invalid; it should bevar runner: any Runnable.Step 2: Verify other parts
Dog conforms correctly, run() returns Void (allowed), and var is allowed. So only missinganyis the error.Final Answer:
Missinganykeyword before Runnable in variable declaration. -> Option AQuick Check:
Existential types needanykeyword [OK]
any before protocol for existential variables [OK]- Omitting
anykeyword - Thinking protocol conformance is missing
- Expecting run() to return a value
Codable protocol and returns its JSON string representation. Which is the correct way to declare the function parameter using existential types?Solution
Step 1: Understand existential vs generic parameters
Usingany Codabledeclares an existential type parameter that can accept any value conforming toCodable. This matches the question requirement.Step 2: Analyze each option
func encodeToJSON(value: Codable) -> String omitsany, which is invalid syntax for existential types. func encodeToJSON(value: T) -> String uses generics, which is valid but not existential. func encodeToJSON(value: Codable & any) -> String has incorrect syntax. func encodeToJSON(value: any Codable) -> String is correct.Final Answer:
func encodeToJSON(value: any Codable) -> String -> Option DQuick Check:
Existential parameter syntax =any Protocol[OK]
any before protocol for existential function parameters [OK]- Using generics instead of existential types
- Omitting
anykeyword - Incorrect syntax with & or angle brackets
Ready to prove it?
Pass the test and this pattern moves unknown
