-2

Very new to Swift. I am really confused as to when you add ( ) and when you do not when returning a return from a nested function. An example is the code below. I know that a nested function is probably not needed, but just as an example:

func areaOfTriangle (width: Double, height: Double) -> Double {
    func divided () -> Double {
        return (width * height) / 2
    }
    return divided()
}

In return divided() portion, I seem to recall somewhere in my learnings that sometimes the ( ) is not needed. Can someone provide some logic as to why the parentheses is needed in this case?

Thanks.

3 Answers3

1

The parentheses in a function call are not needed if the function:

  • Takes only one parameter
  • The parameter itself is a function

For example the function func funcWithHandler(handler: () -> Void) {} can be called like this: funcWithHandler { print("my handler executed") }

Andreas
  • 2,665
  • 2
  • 29
  • 38
0

Use () when you want to execute the function.

return divided()

returns the result of the divided, which is a Double.

return divided

returns a function which returns a Double when executed.

Code Different
  • 90,614
  • 16
  • 144
  • 163
0

This line returns the value of a function call;

return divided()

This line returns the value of a "divided" variable. This variable may also refer to a function (not the value, the function itself);

return divided
Batuhan C.
  • 384
  • 3
  • 10