Existential types (any keyword) in Swift - Time & Space Complexity
We want to understand how using existential types with the any keyword affects the time it takes for a program to run.
Specifically, we ask: How does the program's work grow when we use any types with different input sizes?
Analyze the time complexity of the following code snippet.
protocol Drawable {
func draw()
}
func drawAll(_ items: [any Drawable]) {
for item in items {
item.draw()
}
}
// Usage:
// let shapes: [any Drawable] = [Circle(), Square(), ...]
// drawAll(shapes)
This code calls the draw() method on each item in an array of existential types.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the array and calling
draw()on each element. - How many times: Once for each element in the input array.
As the number of items grows, the number of draw() calls grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 draw calls |
| 100 | 100 draw calls |
| 1000 | 1000 draw calls |
Pattern observation: The work grows directly in proportion to the number of items.
Time Complexity: O(n)
This means the time to run grows linearly with the number of items in the array.
[X] Wrong: "Using any types makes the loop slower in a way that changes the overall time complexity."
[OK] Correct: While any types add some small overhead for dynamic dispatch, the number of operations still grows linearly with input size, so the overall time complexity remains O(n).
Understanding how existential types affect performance helps you explain trade-offs clearly and shows you can reason about code efficiency in real projects.
What if we changed the array to hold concrete types instead of any Drawable? How would the time complexity change?
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
