Understanding Any and Opaque Types in Swift
Choosing the Right Tool for Abstraction
Swift has tools to abstract types, and this lets developers write reusable code in their projects.
Two of these features are Any
and opaque types, that provide ways to work with types. It’s important to disambiguate the two and know when to use each one.
So here is my latest article, examining these two types and their differences, best practices and how to use them.
A Short Comparison
Any in Swift
Any is a type-erased placeholder that can represent any Swift data type including class, struct, functions and more.
This enables an array to store values of different types, for example:
let items: [Any] = [42, "Hello, world!", 12.34, true, CGFloat.pi]
It should be noted that to access the original element you will need to type cast (for example with as?).
I’ve already written an article on this exact topic: https://medium.com/@stevenpcurtis/the-ultimate-type-eraser-swifts-any-f7d34036d6ad