# Functions as function parameters

**URL:** <https://forums.swift.org/t/functions-as-function-parameters/57342>\
**Category:** Using Swift\
**Tags:** function\
**Created:** [May 16, 2022, 12:56am UTC](https://forums.swift.org/t/functions-as-function-parameters/57342 "2022-05-16T00:56:56Z")\
**Posts on this page:** 15\
**Page:** 1

<div class="post-metadata">

**Author:** ![ghard123](https://avatars.discourse-cdn.com/v4/letter/g/d9b06d/32.png) [@ghard123](https://forums.swift.org/u/ghard123)\
**Post date:** [May 16, 2022, 12:56am UTC](https://forums.swift.org/t/functions-as-function-parameters/57342/1 "2022-05-16T00:56:56Z")

</div>

I am having a problem passing functions into a function as a parameter. I want to pass the function 'addOne()' (at the bottom of the below code) into the 'buttonView' function above it. The parameters relate to a button (there are five in the full code), and change the color, the title, and finally the action of the button. In this case it is meant to add 1 to the score. Can someone assist me please?

```swift
 func button(name: String, color: Color) -> some View {
        
        var buttonView: some View {
            
            ZStack {
                Button(action: {
                    addOne()
                }) {
                    Text(name)
                        .fontWeight(.bold)
                        .font(.title)
                        .frame(width: 100, height: 100)
                        .background(color)
                        .cornerRadius(70)
                        .foregroundColor(.black)
                }
                Circle()
                    .stroke(Color.black, lineWidth: 5)
                    .frame(width:150, height: 100)
            }
            
        }
        
        return buttonView
    }
    
    func addOne() {
        score += 1
    }

```

---

<div class="post-metadata">

**Author:** ![Nevin](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nevin/32/617_2.png) [@Nevin](https://forums.swift.org/u/Nevin)\
**Post date:** [May 16, 2022, 1:22am UTC](https://forums.swift.org/t/functions-as-function-parameters/57342/2 "2022-05-16T01:22:33Z")

</div>

I’ve moved this from Evolution to Using Swift.

Could you put triple back-ticks (```) around your code example to format it?

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [May 16, 2022, 1:47am UTC](https://forums.swift.org/t/functions-as-function-parameters/57342/5 "2022-05-16T01:47:10Z")

</div>

> **This will do**
>
> ```swift
> struct ButtonView: View {
> let name: String
> let color: Color
> let execute: () -> Void
>     
> var body: some View {
> ZStack {
> Button(action: execute) {
> Text(name)
> .fontWeight(.bold)
> .font(.title)
> .frame(width: 100, height: 100)
> .background(color)
> .cornerRadius(70)
> .foregroundColor(.black)
> }
> Circle()
> .stroke(Color.black, lineWidth: 5)
> .frame(width:150, height: 100)
> }
> }
> }
> 
> struct ContentView: View {
> var body: some View {
> VStack {
> ButtonView(name: "first", color: .red) {
> print("do first")
> }
> ButtonView(name: "second", color: .green) {
> print("do second")
> }
> ButtonView(name: "third", color: .blue) {
> print("do third")
> }
> }
> }
> }
> 
> ```

---

<div class="post-metadata">

**Author:** ![ghard123](https://avatars.discourse-cdn.com/v4/letter/g/d9b06d/32.png) [@ghard123](https://forums.swift.org/u/ghard123)\
**Post date:** [May 16, 2022, 2:29am UTC](https://forums.swift.org/t/functions-as-function-parameters/57342/6 "2022-05-16T02:29:33Z")

</div>

Thanks Tera. How do I pass in the individual functions to the ButtonView though??

```swift
func addOne() {
        score += 1
    }
    func addTwo() {
        score += 2
    }

```

---

<div class="post-metadata">

**Author:** ![ibex](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ibex/32/30439_2.png) [@ibex](https://forums.swift.org/u/ibex)\
**Post date:** [May 16, 2022, 3:24am UTC](https://forums.swift.org/t/functions-as-function-parameters/57342/7 "2022-05-16T03:24:22Z")

</div>

I have modified @Tera's code to show how to pass in a member function to `ButtonView` 🙂

Here is the key:

```swift
let action: (ButtonView) -> (() -> Void)

```

> **Pass in Individual Functions**
>
> ```swift
> //
> // ContentView.swift
> //
> // ButtonViewPassFunctions
> //
> // Created by ibex10 on 16/5/2022.
> //
> 
> import SwiftUI
> 
> struct ButtonView: View {
> let name: String
> let color: Color
>     
> let action: (ButtonView) -> (() -> Void)
>     
> func execute () -> Void {
> action (self)()
> }
> 
> var body: some View {
> ZStack {
> Button (action: execute) {
> Text(name)
> .fontWeight(.bold)
> .font(.title)
> .frame(width: 100, height: 100)
> .background(color)
> .cornerRadius(70)
> .foregroundColor(.black)
> }
> Circle()
> .stroke(Color.black, lineWidth: 5)
> .frame(width:150, height: 100)
> }
> }
>     
> func addOne() {
> print (#function)
> }
>     
> func addTwo() {
> print (#function)
> }
>     
> func addThree() {
> print (#function)
> }
> }
> 
> struct ContentView: View {
> var body: some View {
> VStack {
> ButtonView (name: "first", color: .red, action: ButtonView.addOne)
> ButtonView (name: "second", color: .green, action: ButtonView.addTwo)
> ButtonView (name: "third", color: .blue, action: ButtonView.addThree)
> }
> }
> }
> 
> struct ContentView_Previews: PreviewProvider {
> static var previews: some View {
> ContentView()
> }
> }
> 
> ```

---

<div class="post-metadata">

**Author:** ![toph42](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/toph42/32/7807_2.png) [@toph42](https://forums.swift.org/u/toph42)\
**Post date:** [May 16, 2022, 6:08pm UTC](https://forums.swift.org/t/functions-as-function-parameters/57342/8 "2022-05-16T18:08:41Z")

</div>

> [@ghard123](#):
>
> How do I pass in the individual functions to the ButtonView though??

I think the answer you’re looking for is this:

```swift
Button(action: addOne)

```

---

<div class="post-metadata">

**Author:** ![ghard123](https://avatars.discourse-cdn.com/v4/letter/g/d9b06d/32.png) [@ghard123](https://forums.swift.org/u/ghard123)\
**Post date:** [May 17, 2022, 2:18am UTC](https://forums.swift.org/t/functions-as-function-parameters/57342/9 "2022-05-17T02:18:42Z")

</div>

Thanks. I am just not sure how to write the parameter for the function. Below I have 'action:' but then what? I appreciate the help with this.

```swift
  func buttonView(name: String, color: Color, action: ????) -> some View {

```

---

<div class="post-metadata">

**Author:** ![Jon\_Shier](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jon_shier/32/921_2.png) [@Jon\_Shier](https://forums.swift.org/u/Jon_Shier)\
**Post date:** [May 17, 2022, 2:22am UTC](https://forums.swift.org/t/functions-as-function-parameters/57342/10 "2022-05-17T02:22:32Z")

</div>

What's the signature that `Button` itself uses? What happens when you use that?

---

<div class="post-metadata">

**Author:** ![ghard123](https://avatars.discourse-cdn.com/v4/letter/g/d9b06d/32.png) [@ghard123](https://forums.swift.org/u/ghard123)\
**Post date:** [May 17, 2022, 11:39am UTC](https://forums.swift.org/t/functions-as-function-parameters/57342/11 "2022-05-17T11:39:59Z")

</div>

Hi Jon and thanks for helping. There are 5 functions that the 5 buttons use (all below). As an example, button 1 will have a label "+1" on it, it will be red, and action the first func below. The second button will have label "+2", be yellow, and perform the second func below, and so on. I can get the labels and colours ok, but I can't get how to pass the below funcs into the main button func as parameters.

```swift
func addOne() {
        score += 1
    }
    func addTwo() {
        score += 2
    }
    func addThree() {
        score += 3
    }
    func reset() {
        score = 0
    }
    func minusOne() {
        score -= 1
    }

```

---

<div class="post-metadata">

**Author:** ![toph42](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/toph42/32/7807_2.png) [@toph42](https://forums.swift.org/u/toph42)\
**Post date:** [May 17, 2022, 11:46am UTC](https://forums.swift.org/t/functions-as-function-parameters/57342/12 "2022-05-17T11:46:37Z")

</div>

> [@ghard123](#):
>
> ```swift
> func addOne() {
> score += 1
> }
> func addTwo() {
> score += 2
> }
> 
> ```

The type of each of those functions is `() -> Void` (a function that takes zero parameters and returns nothing). So, that’s what you’d put as the type of the action parameter:

```swift

func buttonView(name: String, color: Color, action: () -> Void) -> some View {

```

---

<div class="post-metadata">

**Author:** ![ghard123](https://avatars.discourse-cdn.com/v4/letter/g/d9b06d/32.png) [@ghard123](https://forums.swift.org/u/ghard123)\
**Post date:** [May 17, 2022, 12:36pm UTC](https://forums.swift.org/t/functions-as-function-parameters/57342/13 "2022-05-17T12:36:56Z")

</div>

Got it thanks. Can you tell me what I then put in the Button braces to activate action? I have tried inserting 'action', (action), and 'action()', but none work. Again thanks for your help

```swift
func buttonView(name: String, color: Color, action: () -> Void) -> some View {
        
        var buttonView: some View {
            
            ZStack {
                
                Button {
                    
                } label:
                {Text(name)
                        .fontWeight(.bold)
                        .font(.title)
                        .frame(width: 100, height: 100)
                        .background(color)
                        .cornerRadius(70)
                        .foregroundColor(.black)
                }
                Circle()
                    .stroke(Color.black, lineWidth: 5)
                    .frame(width:120, height: 100)
            }
        }
        return buttonView
    }

```

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [May 17, 2022, 1:43pm UTC](https://forums.swift.org/t/functions-as-function-parameters/57342/14 "2022-05-17T13:43:19Z")

</div>

> [@ghard123](#):
>
> but none work

Not just "don't work", they are telling you:  
_Passing non-escaping parameter 'action' to function expecting an @escaping closure_  
or _Escaping closure captures non-escaping parameter 'action'_

The thing it wants is the escaping attribute:

```
func buttonView(name: String, color: Color, action: @escaping () -> Void) -> some View {

```

then you can write either:

```
Button(action: action) {
    Text("Hello, World")
}

```

or:

```
Button {
    action()
} label: {
    Text("Hello, World")
}

```

If you were using the view like I written above "escaping" attribute is assumed:

```
struct ButtonView: View {
    let name: String
    let color: Color
    let execute: () -> Void
    ...
}

ButtonView(..., execute: action) or 
ButtonView(...) { action() }

```

The way you have it is ok, just there is no great need for the internal variable, it could be just:

```
func buttonView(name: String, color: Color, action: @escaping () -> Void) -> some View {
    Button(action: action) {
        ...
    }
}
// i am simplifying, in your case it is ZStack

```

---

<div class="post-metadata">

**Author:** ![toph42](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/toph42/32/7807_2.png) [@toph42](https://forums.swift.org/u/toph42)\
**Post date:** [May 17, 2022, 3:06pm UTC](https://forums.swift.org/t/functions-as-function-parameters/57342/15 "2022-05-17T15:06:08Z")

</div>

You probably figured out the `@escaping` part yourself and are wondering why you don’t see anything change when it calls your function. What you are likely running into is less of a Swift issue and more of an understanding how SwiftUI draws Views issue.

For example, put this in Swift Playgrounds and run it and you’ll see your button and a number of times it’s been tapped above it, but when you tap on it the number stays at zero, despite indications that your addOne function runs every tap.

```swift
import SwiftUI
import PlaygroundSupport

var score: Int = 0

func addOne() {
    score += 1
}

func button(name: String, color: Color, action: @escaping () -> Void) -> some View {
    
    var buttonView: some View {
        ZStack {
            Button(action: action) {
                Text(name)
                    .fontWeight(.bold)
                    .font(.title)
                    .frame(width: 100, height: 100)
                    .background(color)
                    .cornerRadius(70)
                    .foregroundColor(.black)
            }
            Circle()
                .stroke(Color.black, lineWidth: 5)
                .frame(width:150, height: 100)
        }
        
    }
    
    return buttonView
}

struct StaticContentView: View {
    var body: some View {
        VStack {
            Text("\(score)") 
            button(name: "add", color: .primary, action: addOne)
        }
    }
}

PlaygroundPage.current.setLiveView(StaticContentView())

```

The issue here is that SwiftUI doesn’t know the score changed, so it isn’t redrawing. Now, if your model was in an actual `@ObservableObject` and your score `@Published` so SwiftUI can see changes made to the model, then it would know when to redraw.

For example, add this to the playground and you’ll see the score updates are reflected in the View.

```swift
class Scores: ObservableObject {
    @Published var score1: Int = 0
    func addOne() {
        score1 += 1
    }
}

struct DynamicContentView: View {
    @ObservedObject var model = Scores()
    var body: some View {
        VStack {
            Text("\(model.score1)")
            button(name: "add", color: .primary) { model.addOne() }
        }
    }
}

PlaygroundPage.current.setLiveView(DynamicContentView())

```

I very highly recommend watching the Stanford CS193p class that’s available for free on YouTube and it will teach you a great deal about SwiftUI.

---

<div class="post-metadata">

**Author:** ![ghard123](https://avatars.discourse-cdn.com/v4/letter/g/d9b06d/32.png) [@ghard123](https://forums.swift.org/u/ghard123)\
**Post date:** [May 18, 2022, 12:57am UTC](https://forums.swift.org/t/functions-as-function-parameters/57342/16 "2022-05-18T00:57:29Z")

</div>

Wow. That helps heaps. Thanks Tera and Toph for all of the assistance. Greg

---

<div class="post-metadata">

**Author:** ![ghard123](https://avatars.discourse-cdn.com/v4/letter/g/d9b06d/32.png) [@ghard123](https://forums.swift.org/u/ghard123)\
**Post date:** [May 18, 2022, 12:58am UTC](https://forums.swift.org/t/functions-as-function-parameters/57342/17 "2022-05-18T00:58:03Z")

</div>

I have started the Stanford course. It looks fantastic.
