UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Possible to return Opaque Type from Closure???

Forums > Swift

Is it possible to use opaque types in closures?

For example, I was hoping to be able to define a closure that returns some SwiftUI view.

var makeView: () -> (some View)

Error that Xcode gives is:

'some' types are only implemented for the declared type of properties and subscripts and the return type of functions

3      

Swift has no way of knowing what the return type of that closure is supposed to be. Even though the some keyword hides the type from the caller, the compiler still needs to know what that type is.

3      

The only way I can think of to sort of make this work is to make your wrapping struct or class generic over a parameter conforming to View, then use that parameter as the return type of the closure. This is how I usually setup my structs:

struct MyStruct<Content> where Content: View {
    let content: Content

    init(content: () -> Content) {
        self.content = content()
    }
}

If you don't want to have a generic view you can make only the initializer generic, then wrap the content in AnyView to erase the type, like so:

struct MyStruct {
    let content: AnyView

    init<Content>(content: () -> Content) where Content: View {
        self.content = AnyView(content())
    }
}

3      

Hacking with Swift is sponsored by Superwall

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.