Trying to implement custom functionality to a SwiftUI button, keep getting a warning

Viewed 35

I am trying to make a custom button where I can implement my own functionality, like in the example below:

MSButton {
    print("hello")
}

Problem is, I keep getting the Expression of type '(() -> Void)?' is unused warning, and the functionality I add doesn't activate.

Here is the code I made in an attempt to implement this:

struct MSButton: View {
    
    var action: (() -> Void)?
    
    var body: some View {
        Button() {
            action // where I am getting the warning.
        } label: {
            Text("Button")
        }
    }
}

What am I missing that would allow me to get my action to work properly? Any help would be greatly appreciated.

2 Answers

I was able to figure it out. My implementation is below:

struct MSButton: View {
    
    var action: (() -> Void)?
    
    var body: some View {
        Button() {
            self.action!() // fixed line
        } label: {
            Text("Button")
        }
    }
}

It works, although I don't understand exactly why this works, rather than the code I wrote in my question.

The answer is quite simple, you forgot to call it as a function. Therefore, the correct answer is self.action?()

I personally would recommend to set it up like this

struct MSButton: View {
    var action: (() -> Void) = { }
    var body: some View {
        Button() {
            self.action()
        } label: {
            Text("Button")
        }
    }
}
Related