Swift For-Each Loop

Swift For-Each Loop

Use forEach to iterate sequences with a closure.


Iterate with forEach closures

Pass a closure to forEach to process each element of a sequence.

Example

["A","B","C"].forEach { print($0) }


Enumerated forEach

Use enumerated() with forEach to get index and value.

Example

let items = ["A","B","C"]
items.enumerated().forEach { print("\($0.offset): \($0.element)") }

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *