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?✗ Incorrect
The
any keyword marks a type as existential, meaning it can hold any value conforming to the specified protocol.Which of the following is a correct way to declare an existential type variable for protocol
Equatable?✗ Incorrect
Using
any Equatable explicitly declares an existential type variable.Why is using
any keyword recommended over omitting it for existential types?✗ Incorrect
The
any keyword makes it clear the type is existential, improving readability and safety.Can you assign a value of a concrete type conforming to a protocol to a variable declared as
any Protocol?✗ Incorrect
Existential types can hold any value conforming to the protocol, including concrete types.
How do you declare a variable that conforms to both
Codable and Hashable using existential types?✗ Incorrect
You combine protocols with & and prefix with
any to declare an existential type conforming to multiple protocols.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.