Search code examples
swiftclosures

Swift: reproducing forEach, viewing source code?


I am currently learning closures and I think I have it but I am interested in reproducing the forEach method of an array. I would like to see how its done. In xcode I can see the declaration which shows

@inlinable public func forEach(_ body: (Element) throws -> Void) rethrows

but what i really want to see is the actually code.

For example the following

var items = [1,2,3]
items.forEach { (item) in
    print(item)
}

I am interested in how the closure has access to (item), how is forEach providing this information.

The closure is my code and it receives the first variable which I have named "item", of course it works but i wanted to know how.

If I wanted to create a new version of forEach, lets call it forEachNew then how would i do this.

Is the forEach an extension over a specific type/ protocol ?

Any help really appreciated.

Thanks


Solution

  • You can check the current implementation of Sequence.forEach on GitHub, since Swift is open-source.

    The current implementation simply uses a for ... in loop to iterate through the Sequence and then executes the body closure for each element.

    @inlinable
      public func forEach(
        _ body: (Element) throws -> Void
      ) rethrows {
        for element in self {
          try body(element)
        }
      }
    }