30

I have seen closures in Swift use $0 internally and sometimes they use $1. What exactly is $0 and what are other $X can you use?

Here are examples of it in use:

applyMutliplication(2, {$0 * 3})
array.map({$0 + 1})
pkamb
  • 33,281
  • 23
  • 160
  • 191
lostAtSeaJoshua
  • 1,695
  • 2
  • 21
  • 34
  • Possible duplicate of: [What does $0 and $1 mean in Swift Closures?](https://stackoverflow.com/questions/36144322/what-does-0-and-1-mean-in-swift-closures) – pkamb Sep 08 '20 at 17:26

1 Answers1

31

It's a shorthand argument name.

From the Swift Book:

“Swift automatically provides shorthand argument names to inline closures, which can be used to refer to the values of the closure’s arguments by the names $0, $1, $2, and so on.”

— Apple Inc. “The Swift Programming Language.”

It helps reduce the verbosity of your code (sometimes at the cost of readability), so you don't have to write out long argument lists when defining closures.

cmyr
  • 2,235
  • 21
  • 30
Andy Obusek
  • 12,614
  • 4
  • 41
  • 62
  • 21
    Because verbosity can provide understandability. – zaph Dec 15 '14 at 19:58
  • 1
    Yea, you are right, sometimes verbostiy does help readability and understandability, though that starts to border into opinion. Either way I updated my answer. – Andy Obusek Dec 15 '14 at 20:00
  • Nice change. Reducing the writing out of long argument lists is not the end goal, that happens only one and there is auto-completion to help. The end goal should be readability since the code will generally be read many times. – zaph Dec 15 '14 at 20:04
  • While there are no argument in the closure, what will be $0 referred to?(The caller self?) – A.C Mar 29 '15 at 23:54
  • ok.. but what if I need to use closure inside closure? if I reffer again to $0 will it think of .. as the same variable? example : TransformOf<[Int], [String]>(fromJSON: {$0!.map($0!.toInt())}, toJSON: {$0!.map("\(($0))")})..... i need this function to take the first "fromJSON" closure a [String] and transform it to [Int] and the second closure do the reversed stuff.. but it will never compile nor it will compile if I do ... TransformOf<[Int], [String]>(fromJSON: {($0! as [String]).map($0!.toInt())}, toJSON: {($0! as [Int]).map("\(($0))")}).. Please advice – Fawkes Jul 30 '15 at 17:58