Forge
Forge

Reputation: 6844

What does the expression () -> () = {} mean in Swift?

I'm going over some Swift code and I've encounter this function signature:

func foo(withCompletion completion: @escaping () -> () = {}) { ... }

I'm not sure what does the part () -> () = {} mean? And if it's a default value, how should it be used?

Any idea?

The code is in Swift 3

Upvotes: 3

Views: 94

Answers (1)

rmaddy
rmaddy

Reputation: 318954

The completion argument has a type of () -> (). That's a closure that has no parameters and has an empty (void) return type.

The = {} is the default value for the parameter meaning that you don't actually need to pass in a closure if you don't need one.

So you can call this as:

foo(withCompletion: {
    // your code here
})

or (using trailing closure syntax):

foo() {
    // your code here
}

or (if you don't want to use the completion closure):

foo()

Upvotes: 7

Related Questions