0
0
Swiftprogramming~5 mins

Existential types (any keyword) in Swift - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an existential type in Swift?
An existential type is a type that can hold any value conforming to a specific protocol or set of protocols. It allows you to work with values of different types through a common interface.
Click to reveal answer
beginner
What does the any keyword do in Swift?
The any keyword explicitly marks a type as an existential type, meaning it can hold any value conforming to the specified protocol. It clarifies that the value is not a specific type but any type that fits the protocol.
Click to reveal answer
beginner
How do you declare a variable that can hold any type conforming to a protocol Drawable using the any keyword?
You declare it like this: <br>var shape: any Drawable<br>This means shape can hold any value that conforms to the Drawable protocol.
Click to reveal answer
intermediate
Why did Swift introduce the any keyword for existential types?
Swift introduced any to make it clear when a type is existential, improving code readability and safety by distinguishing between concrete types and existential types.
Click to reveal answer
intermediate
Can you use existential types with multiple protocols? How?
Yes, you can combine multiple protocols using the any keyword like this: <br>var value: any ProtocolA & ProtocolB<br>This means value can hold any type conforming to both ProtocolA and ProtocolB.
Click to reveal answer
What does the any keyword in Swift indicate?
AA type alias
BA concrete type is used
CA generic type parameter
DA value can be any type conforming to a protocol
Which of the following is a correct way to declare an existential type variable for protocol Equatable?
Avar item: Equatable
Bvar item: <Equatable>
Cvar item: any Equatable
Dvar item: Equatable & any
Why is using any keyword recommended over omitting it for existential types?
AIt improves code clarity and safety
BIt makes code run faster
CIt allows inheritance
DIt disables protocol conformance
Can you assign a value of a concrete type conforming to a protocol to a variable declared as any Protocol?
ANo, only existential types are allowed
BYes, because the variable accepts any conforming type
COnly if the concrete type is a class
DOnly if the concrete type is a struct
How do you declare a variable that conforms to both Codable and Hashable using existential types?
Avar data: any Codable & Hashable
Bvar data: Codable & Hashable
Cvar data: any Codable, Hashable
Dvar data: Codable | Hashable
Explain what existential types are in Swift and how the any keyword is used with them.
Think about how you can hold different types that share a protocol.
You got /3 concepts.
    Describe the benefits of using the any keyword explicitly in your Swift code.
    Why does Swift want you to write <code>any</code> now?
    You got /3 concepts.