skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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")
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search