Back to Home
Opaque Types in Swift

Opaque Types in Swift

  • 24 Jan 2023 |
  • 01 Min read

TL;DR

Opaque types give us the possibility to describe the expected return type without defining the specific return type. What? Ok, lets give it another try: Functions with an opaque return type, have to return values of only one specific type (unlike protocol types where the return type only has to conform to the defined protocol). At first this sounded super confusing to me, but after a while I think it sank in.

The Problem Opaque Types Solve

The use of the some keyword is the crucial part, here - I didn't notice that for a while:


var body: some View { ... }

This allows the Swift compiler to actually see the effectively used type information beforehand. For example, the compiler can see the following return types:


var body: some View {
  HStack {
    ...
  }
}

var body: some View {
  Text {
    ...
  }
}

With that we give the compiler more information about the one and only specific type we are using and so it can optimize the code for us. If we would use the naked protocol instead:


var body: View {
  Text {
    ...
  }
  VStack {
    ...
}

we would actually be able to return different types of Views but the compiler could not optimize the code anymore and make it more difficult for the caller/implementor to handle different return types.

Conclusion

We can use opaque type (constraints) to hide the concrete types away from the caller/implementors and help us to improve readability and simplicity of our code. Remember: Opaque types need to be fixed for the scope of the value, so we can’t return different types within the same method scope.

Learn, smile, help and be happy, cheers 🙂


References

Related Posts