Callback Function As Parameter

My sample function is this

func temp(type: String, callback: (() -> Void)? = nil) {
  callback?()
}

But why can't I do this?

temp(type: "Here", () -> {
   print("hey")
})

It says, Expected type after '->'

While this does work

temp(type: "Here",  { () -> Void in
   print("hey")
})

I find it weird why the () -> Void has to be inside the closure.

Answered by Scott in 746083022

Even better, you can use the concise and stylish trailing closure syntax:

temp(type: "Here") {
   print("hey")
}

Also, consider keeping the callback argument label. With trailing closure syntax you don’t use it anyway, and it improves clarity if you pass a method or function name instead of a literal closure block, like this:

temp(type: "Here", callback: methodOrFunctionThatPrintsHey)

The second one probably doesn't compile either. Need a label for callback:

temp(type: "Here",  callback: { () -> Void in
   print("hey")
})

When you write

temp(type: "Here", () -> {
   print("hey")
})

with an explicit -> signalling that you will define the type of the return, you have to tell the type of the return. Logical.

But you can write:

temp(type: "Here", callback: {
   print("hey")
})

Note:

if you mute the second label:

func temp(type: String, _ callback: (() -> Void)? = nil) {
  callback?()
}

Then you can write:

temp(type: "Here", {
   print("hey")
})

temp(type: "Here", { () -> Void in
   print("hey")
})
Accepted Answer

Even better, you can use the concise and stylish trailing closure syntax:

temp(type: "Here") {
   print("hey")
}

Also, consider keeping the callback argument label. With trailing closure syntax you don’t use it anyway, and it improves clarity if you pass a method or function name instead of a literal closure block, like this:

temp(type: "Here", callback: methodOrFunctionThatPrintsHey)

Seems ill have to read up on closures. Thanks!

Callback Function As Parameter
 
 
Q