To create a for each
loop in Swift, you can use the for-in
loop.
Here's an example that shows how to iterate over an array of strings:
main.swift93 chars6 lines
This will output:
main.swift25 chars5 lines
In this example, we declare an array of strings called fruits
, which contains four elements. We then use a for-in
loop to iterate over each element in the array. For each iteration, the value of the current element is assigned to the constant fruit
. We then print the value of fruit
.
This works for iterating over any collection that conforms to the Sequence
protocol in Swift.
gistlibby LogSnag