< When would you use closures with return values as parameters to a function? | How many parameters can a closure take? > |
Updated for Xcode 13.3
When working with closures, Swift gives us a special shorthand parameter syntax that makes it extremely concise to write closures. This syntax automatically numbers parameter names as $0
, $1
, $2
, and so on – we can’t use names such as these in our own code, so when you see them it’s immediately clear these are shorthand syntax for closures.
As for when you should use them it’s really a big “it depends”:
$3
or $4
that you need to compare against $0
Give them actual names and their meaning becomes clearer.$0
means.$0
more than maybe two or three times, you should probably just give it a real name.What matters is that your code is easy to read and easy to understand. Sometimes that means making it short and simple, but not always – choose shorthand syntax on a case by case basis.
SPONSORED Spend less time managing in-app purchase infrastructure so you can focus on building your app. RevenueCat gives everything you need to easily implement, manage, and analyze in-app purchases and subscriptions without managing servers or writing backend code.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.