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