iosswiftswiftui

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

@State private var isDark = false

...

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

Solution

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

    Here is a working implementation of your button:

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