Opaque Types in Swift
Opaque types in Swift are a Swift 5.1 feature that allows a function and computed properties to return any value that conforms to a specific protocol without revealing the exact type. This is particularly useful for hiding implementation details and enhancing type safety in your code. Opaque types are denoted by the keyword some
and are widely used in Swift development to improve code abstraction and maintainability.
let's understand it with an example
In the example below, the getMoneyWithoutTax function returns an Int concrete type, while the getMoneyWithTax(val:Int) returns an Opaque Type which in this case is Equatable and so since integers conform to Equatable this works just fine.
similarly, this concept is used a lot in SwiftUI.
in the SwiftUI body, the rule is we can return any type that conforms to the View Protocol, which includes many different views Vstack, Image, Text, as well as your own custom views:
Opaque types are beneficial for several reasons:
- Type Safety: They improve the type safety of your Swift code by ensuring that the returned object conforms to a specific protocol.
- Flexibility: They allow you to use generic code while still returning specific types, making your code more flexible and adaptable.