Start a Project

Opaque Types in Swift

Swift 5.1 introduces Opaque return types as a new language feature. It can be used to return a value’s type for functions and properties without demonstrating the concrete type of the value. The return type will be of some type that implements the protocol.

Wrap-type information can be used at boundaries between any module and source code. Because the type of the return value can remain secret. Unlike returning a value whose type is a protocol type, opaque types preserve type identity—the compiler has access to the type information, but clients of the module don’t.

It always refers to one specific, concrete type – which is hidden from us while in the case of the protocol type can refer to many types, as they conform to the protocol.

Implementation of Opaque Types

To more clarification about the opaque return type and why it is different than just using the protocol as a return type. Let’s discuss with examples how we can use it.

Declaring Protocol with associatedtype:

Associated types are a powerful way of making protocols generic or opaque, but they can be a bit confusing at first.
Let’s add a protocol called Vehicle. This protocol has an associatedtype called Type. Vehicle protocol that can store any type those items depend on whatever conforms to the protocol, but we can still use them inside the protocol and any extensions.

Concrete types of the Protocol:

Now add three concrete types for this protocol as OnRoad, OnSKy and OnWater. All are different types as

Here, OnRoad conforms to the protocol with parameter as Car type and that returns the type as Car.

OnWater conforms to the protocol with parameter as Boat type and that returns the type as Boat.

And OnSky conforms to the protocol with parameter as well as returns the type as Boat.

Handle Cases of Vehicle Protocol:

Now for handling the case of Vehicle protocol values defined in an enumeration as:

Returning an Opaque Type:

Now we’re going to define a function like this:

The returns a value of type Vehicle and uses some keyword to denote that this is an opaque type. It’s up to the function to get what concrete type is returned. Above written function returning the different values in the bodies.

Printed out the result of its return type of functions.

Conclusion

I hope this blog will help you in the understanding of Opaque type if you have any comments, questions, or recommendations, feel free to post them in the comment section below!

For other blogs, please click here.

Exit mobile version