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 do I provide function as a parameter of struct

I’m learning SwiftUI. So I am creating weather app with @state toggling. I created button view but I’m struggling with passing isDark.toggle function as a parameter for my button view. I get Escaping autoclosure captures 'inout' parameter 'self'

I’ve my button view

struct WeatherButton: View {
    var text: String
    var action: () -> Void
    
    init(text: String, action: @escaping () -> Void) {
        self.text = text
        self.action = action
    }
    
    var body: some View {
        Button(action: {
            action()
        }, label: {
            Text(text)
                .frame(width: 280, height: 50)
                .background(.white)
                .font(.system(size: 20, weight: .bold))
                .cornerRadius(10)
        })
    }
}

and how i use it

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

@State private var isDark = false

...

WeatherButton(text: "Theme toggle doesn't work",
                              action: isDark.toggle)

>Solution :

You’re seeing this error because toggle is a mutating function, and you are trying to pass it directly as a closure without explicitly capturing self. You can use a closure to capture self explicitly to avoid this issue.

Here is a working implementation of your button:

WeatherButton(text: "Theme toggle doesn't work") { self.isDark.toggle() }
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