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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.