-2

I am following this tutorial: https://www.hackingwithswift.com/books/ios-swiftui/building-a-basic-layout

However, that code won’t work and in fact means something quite different. If we add the parentheses after calculateBedtime it means “call calculateBedtime() and it will send back to the correct function to use when the button is tapped.” So, Swift would require that calculateBedtime() returns a closure to run.

By writing calculateBedtime rather than calculateBedtime() we’re telling Swift to run that method when the button is tapped, and nothing more; it won’t return anything that should then be run

Button(action: calculateBedtime()) {
    Text("Calculate")
}

Button(action: calculateBedtime) {
    Text("Calculate")
}

What is the difference between these two ? I couldnt understand Paul Hudson explanation very well. Everytime I call a function i put () this time why i need to omit () ?

DrainOpener
  • 186
  • 1
  • 18
  • 4
    You omit the `()` because you aren't calling the function, you're passing it to the button so that the button can call it when it wants to – dan Jul 27 '21 at 21:43
  • 1
    @DrainOpener: It is not just about having or not having `()` if you want pass a function as variable or value you need closure you cannot sign a function to a value unless that function returns a Value in that case you are passing the value not function. – ios coder Jul 27 '21 at 22:10
  • https://stackoverflow.com/questions/67341566/a-function-with-parameters-that-doesnt-require-its-parameters-at-the-call-site/67341772#67341772 – matt Jul 28 '21 at 00:09

1 Answers1

0

Something important to remember - closures are reference types. When you 'call' the closure with () you are running that code within the closure.

The action parameter is of type () -> Void, which is the same as the calculateBedtime closure.

These two are equivalent:

Button(action: calculateBedtime) {
    Text("Calculate")
}
Button(action: {
    calculateBedtime()
}) {
    Text("Calculate")
}
George
  • 25,988
  • 10
  • 79
  • 133