Instance Method


Calls the given closure on each element in the sequence in the same order as a for-in loop.


func forEach(_ body: (UInt8) throws -> Void) rethrows



A closure that takes an element of the sequence as a parameter.


The two loops in the following example produce the same output:

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

numberWords.forEach { word in
// Same as above

Using the forEach method is distinct from a for-in loop in two important ways:

  1. You cannot use a break or continue statement to exit the current call of the body closure or skip subsequent calls.

  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.

See Also

Iterating Over Bytes

func enumerated() -> EnumeratedSequence<Data>

Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero and x represents an element of the sequence.

func makeIterator() -> Data.Iterator

Returns an iterator over the contents of the data.

struct Data.Iterator

An iterator that operates over the contents of data.

func enumerateBytes((UnsafeBufferPointer<UInt8>, Data.Index, inout Bool) -> Void)

Enumerates the contents of the data's buffer.