Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: how to skip unused closure arguments

Tags:

swift

Given a function signature:

func myFunc(someClosure: (argA: TypeA!, argB: TypeB!) -> Void)

sometimes I don't need the passed parameters to the closure so the call is:

myFunc { (_,_) in  
    //bla bla
}

is there a way to skip this redundant (_,_) in part?

like image 981
Amr Lotfy Avatar asked Apr 03 '16 16:04

Amr Lotfy


People also ask

What is an escaping closure Swift?

An escaping closure is a closure that's called after the function it was passed to returns. In other words, it outlives the function it was passed to. A non-escaping closure is a closure that's called within the function it was passed into, i.e. before it returns.

What is Clouser in Swift?

In Swift, a closure is a special type of function without the function name. For example, { print("Hello World") } Here, we have created a closure that prints Hello World . Before you learn about closures, make sure to know about Swift Functions.

How do you pass closure to a function?

If we wanted to pass that closure into a function so it can be run inside that function, we would specify the parameter type as () -> Void . That means “accepts no parameters, and returns Void ” – Swift's way of saying “nothing”.


2 Answers

There is no way to skip it entirely, but if you won't use either argument, you can use

myFunc { _ in
    // do stuff
}

Similarly, if you only need one of the arguments, you can use

myFunc { _, something in
    // do stuff
}
like image 116
Tim Vermeulen Avatar answered Nov 03 '22 23:11

Tim Vermeulen


Personally I don't like turning parameters into ( _ ), so I use ( _ paramName ) (Swift 3, Xcode 8.3 beta)

like image 29
Matt H Avatar answered Nov 03 '22 22:11

Matt H