for each in swift

In Swift, you can use the for-in loop to loop over a sequence, such as an array, a dictionary, a range, or a string. The for-in loop is also commonly referred to as a for-each loop.

Here's an example of how to use a for-in loop to loop through an array of strings:

main.swift
let names = ["Alice", "Bob", "Charlie"]

for name in names {
    print(name)
}
79 chars
6 lines

This code will loop through the names array and print each name to the console.

You can also use the for-in loop with a dictionary to loop through its key-value pairs:

main.swift
let ages = ["Alice": 30, "Bob": 25, "Charlie": 35]

for (name, age) in ages {
    print("\(name) is \(age) years old")
}
121 chars
6 lines

This code will loop through the ages dictionary and print each name and age to the console.

In addition to arrays and dictionaries, you can use the for-in loop to loop through other sequences, such as a range of numbers:

main.swift
for i in 1...5 {
    print(i)
}
32 chars
4 lines

This code will loop through the range 1...5 and print each number to the console.

gistlibby LogSnag