Opaque Type In Swift
Opaque Return Types is a feature added in Swift 5.1. It comes to fix a fundamental problem of the usage of protocols and the design of Swift APIs. It can be used to return some value for function/method , and property without revealing the concrete type of the value to client that calls the API.
We all are well aware about using protocol as a return type. Using Protocol as return type means, we are providing protocol as the return type of the function. Like in below example, we are returning Shape protocol type in the function getShapeType() and later we can typecast that protocol type according to our usage as done at line number 138.
Now, let’s imagine a scenario where we are not knowing the datatype of draw() method used in protocol Shape. Let’s start making things more Generic. Yes, Correct I am talking about associatedType now. Once, our protocol starts having associatedType, compiler will starts providing error at compilation time while returning protocol type. The main reason behind this error is that, we have made our protocol Generic so it doesn’t have their own dataType and it will follow the dataType from the conforming struct, classes or enums.
Now, Let’s fix this issue. Opaque Type comes in feature to fix this issue. Opaque type doesn’t know the internal datatype of the protocol rather it uses some keyword to inform compiler that return type could be of that particular protocol type.
Let’s solve this interesting problem using Opaque Type.