Swift: 重现 forEach,查看源代码?

huangapple go评论124阅读模式
英文:

Swift: reproducing forEach, viewing source code?

问题

我目前正在学习闭包,我觉得我已经理解了,但我对复制数组的forEach方法很感兴趣。我想看看它是如何实现的。在Xcode中,我可以看到声明,其中显示了:

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

但我真正想看到的是实际的代码。

例如,以下代码块:

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

我对闭包如何访问(item)感兴趣,forEach如何提供这些信息。

闭包是我的代码,它接收了我命名为“item”的第一个变量,当然它能正常工作,但我想知道它是如何实现的。

如果我想创建一个新版本的forEach,让我们称它为forEachNew,那么我该如何做呢?

forEach是针对特定类型/协议的扩展吗?

非常感谢任何帮助。

英文:

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

答案1

得分: 3

你可以在GitHub上查看Sequence.forEach的当前实现,因为Swift是开源的。

当前的实现简单地使用for ... in循环来迭代Sequence,然后对每个元素执行body闭包。

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

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)
    }
  }
}

huangapple
  • 本文由 发表于 2020年1月6日 22:14:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613632.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定