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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out 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.