0

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.

  • Does [this](https://stackoverflow.com/q/67012282/5133585) answer your question? Look at how they have passed the action. – Sweeper Sep 13 '22 at 03:05
  • @Sweeper The implementation I'm looking for seems to be different than how the post you linked goes about solving it. –  Sep 13 '22 at 03:13
  • Please describe *how* exactly it is different. What is "the implementation you're looking for"? – Sweeper Sep 13 '22 at 03:16
  • @Sweeper I was able to figure it out. You can see my answer below to see what I was trying to do. –  Sep 13 '22 at 03:20
  • https://stackoverflow.com/a/24978078/6433023 – Nirav D Sep 13 '22 at 04:03

2 Answers2

0

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.

  • https://stackoverflow.com/a/24978078/6433023 – Nirav D Sep 13 '22 at 04:03
  • It would be safer to say `self.action?()`. When you force unwrap you risk a crash. This code works because you are invoking the closure via `()` In your original code you weren't. You had the equivalent of `2` just sitting there, so the compiler tells you that you aren't doing anything with the value – Paulw11 Sep 13 '22 at 11:07
0

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")
        }
    }
}