NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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

1      

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.

1      

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())
    }
}

1      

Hacking with Swift is sponsored by Essential Developer

SPONSORED From March 20th to 26th, you can join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer!

Click to save your free spot now

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.