Member-only story

Understanding Opaque Return Types in Swift

Alfian Losari
7 min readSep 8, 2019

--

You can also read this article in my Xcoding With Alfian blog website using the link below.

Opaque return types is a new language feature that is introduced in Swift 5.1 by Apple. 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. The return type will be some type that implement a protocol. Using this solution, the module API doesn’t have to publicly leak the underlying internal return type of the method, it just need to return the opaque type of the protocol using the some keyword. The Swift compiler also will be able to preserve the underlying identity of the return type unlike using protocol as the return type. SwiftUI uses opaque return types inside its View protocol that returns some View in the body property.

Here are some of the essential things that opaque return types provides to keep in our toolbox and leverage whenever we want to create API using Swift:

  1. Provide a specific type of a protocol without exposing the concrete type to the API caller for…

--

--

Alfian Losari
Alfian Losari

Written by Alfian Losari

Mobile Developer and Lifelong Learner. Currently building super app @ Go-Jek. Xcoding with Alfian at https://alfianlosari.com

Responses (8)