Swift Concepts: Opaque Types & Existential Types
This article delves into the theory and practice of using any
and some
, elucidating their roles, differences, and practical applications in app development.
Introduction
Swift, the powerful and intuitive programming language for macOS, iOS, watchOS, and tvOS app development, continues to evolve. With the introduction of Swift 5.1, two new keywords, any
and some
, have been added to handle types more effectively: opaque types and existential types. Understanding these keywords is essential for both beginner and expert developers to write efficient and robust Swift code.
Theory
Explanation for Beginners
Opaque Types (some
)
Opaque types, introduced with the some
keyword, allow you to specify a type without revealing its exact type. This can be particularly useful when you want to abstract the details of the return type while ensuring it conforms to a protocol.
Example:
func makeShape() -> some Shape {
return Circle()
}
Here, makeShape
returns a type that conforms to the Shape
protocol, but the exact type is hidden (opaque).