Instance Method インスタンスメソッド

forEach(_:)

Calls the given closure on each element in the sequence in the same order as a for-in loop. 指定されたクロージャをそのシーケンスの各要素上でfor-inループと同じ順番で呼び出します。

Declaration 宣言

func forEach(_ body: (Base.Element) throws -> Void) rethrows

Parameters パラメータ

body

A closure that takes an element of the sequence as a parameter. あるクロージャ、それはシーケンスの1要素を引数として取ります。

Discussion 解説

The two loops in the following example produce the same output: 以下の例における2つのループは、同じ出力を生み出します:


let numberWords = ["one", "two", "three"]
for word in numberWords {
    print(word)
}
// Prints "one"
// Prints "two"
// Prints "three"


numberWords.forEach { word in
    print(word)
}
// Same as above

Using the forEach method is distinct from a for-in loop in two important ways: forEachメソッドを使うことは、for-inループとは2つの重要なやり方においてまったく異なります:

  1. You cannot use a break or continue statement to exit the current call of the body closure or skip subsequent calls. あなたは、breakまたはcontinue文を使って、bodyクロージャの現在の呼び出しを抜け出したり、または続いて起こる呼び出しを飛ばしたりできません。

  2. Using the return statement in the body closure will exit only from the current call to body, not from any outer scope, and won’t skip subsequent calls. return文をbodyクロージャにおいて使うことは、ただ現在のbodyへの呼び出しから抜け出すだけです、全く外側のスコープからではなくて、そして続いて起こる呼び出しを飛ばしません。