What is the advantage of using opaque type?

I tried practicing using it. but I couldn't figure any use case.

Go experiment with SwiftUI, and disallow yourself from using it. This will be the best teacher.

3 Likes

You can see another use case in Vapor's Redis library.

In this method, we can only ever return the exact same type - a generic RedisSessionDriver using the concrete type of RedisSessionsDelegate passed into the method - so we can use the some keyword to keep all of this type information with the compiler.

This provides 2 primary benefits:

  1. This return value can be passed to generic methods that accept SessionDriver arguments
    eg. func load<Driver: SessionDriver>(_ driver: Driver)
  2. Using the return type avoid performance overhead of using it as an existential, however minor it could be. (static dispatch vs dynamic dispatch)

what i feel is hide away the real type on purpose.

Terms of Service

Privacy Policy

Cookie Policy