Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i import view which bring a closure with itself in SwiftUI?

Here is my code, it does not work:

struct ContainerView<MyContent: View>: View {

    let myContent: () -> MyContent
    @State private var myValue: String = ""
    
    var body: some View {
        
        myContent() { value in
            
            myValue = value
        }
        
    }

}

I want make this logic works, when I am bringing my view as myContent to body, I want be able to bring a string value with it like in code! I am not looking for reaching my goal with other ways, the goal of this question is be able to access value like in code as clouser.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Warning: I’m not sure what the use-case of this is — it’s not clear what problem is trying to be solved here, but there’s likely a better fit that trying to make something like this work. This answer, though, does solve the compilation errors presented above.


Your syntax inside body implies that you want a trailing closure on myContent, but it’s not defined in the signature. This would solve the compilation error:

struct ContainerView<MyContent: View>: View {

    let myContent: (@escaping (String) -> Void) -> MyContent
    @State private var myValue: String = ""
    
    var body: some View {
        Text(myValue)
        myContent() { value in
            myValue = value
        }
    }
}

Call site:

ContainerView { closure in
  Button("Test") {
    closure("Value")
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading