# seq.forEach()

{% hint style="danger" %}
* ⛔ <mark style="color:purple;">**break**</mark> : not allowed.
* ⛔ <mark style="color:purple;">**continue**</mark> : not allowed.&#x20;
* ❗ <mark style="color:purple;">**return**</mark> : <mark style="color:red;">**exit only from the current call**</mark> to <mark style="color:purple;">**body**</mark>. :point\_right: :digit\_one:
{% endhint %}

```swift
// `seq.forEach(_:)` declaration:
func forEach(
    _ body: (Self.Element) throws -> Void
) rethrows
```

{% tabs %}
{% tab title="1" %}
```swift
// sequence.forEach()
(1...10).forEach { n in 
    print(n)
    // ⭐️ return from this closure, not from the `forEach` method
    if n > 2 { return } 
}
// 1, 2, ..., 10
```
{% endtab %}

{% tab title="2" %}
```swift
class ArticleGroupViewController: UIViewController {

    private let articles: [Article]

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // ⭐️ 直接將 method 放入 forEach()，可增加程式的可讀性。
        articles.forEach(addArticleView)
    }

    private func addArticleView(for article: Article) {
        let articleView = ArticleView()
        view.addSubview(articleView)
    }
}
```
{% endtab %}

{% tab title="📘 手冊" %}
* Collections ⟩ [Sequence](https://developer.apple.com/documentation/swift/sequence) ⟩ [.forEach(\_:)](https://developer.apple.com/documentation/swift/sequence/3018369-foreach)
* Flow Control ⟩ [for-in loop](https://docs.swift.org/swift-book/LanguageGuide/ControlFlow.html#ID121) - iterate over a sequence (array, range, string, dictionary)
{% endtab %}

{% tab title="📗 參考" %}
* [ ] Advanced Swift, p.&#x20;
* [x] Sundell ⟩ [Picking between a for loop and forEach](https://www.swiftbysundell.com/tips/picking-between-for-and-for-each/)
{% endtab %}

{% tab title="👥 相關" %}
* [Broken link](broken-reference "mention") ⟩ [for...in](../../flow/loop/for...in "mention") ⭐️
{% endtab %}
{% endtabs %}

## forEach vs. for-in loop

