Swift forEach

In this tutorial, we will learn about Swift forEach with example programs.

Swift forEach is an instance method, meaning forEach method can be applied only on instances, like an array instance, set instance, dictionary instance, etc.

Swift forEach implements the given set of instructions on each element of the sequence like an array, set, dictionary, etc.

Following is a simple example to use forEach on an instance.

sequenceInstance.forEach{ item_identifier in
    // set of instructions
    // you can use "item_identifier" identifier to access this element
}

You can access this item in the loop with the item_identifier you provided after forEach keyword.

in after item_identifier is a keyword.

Example 1 – forEach with an Array

In this example, we take an array of numbers and use forEach to print each element.

main.swift

var odds:[Int] = [3, 9, 7, 5]

odds.forEach{ odd in
    print(odd)
}

Output

3
9
7
5
ADVERTISEMENT

Example 2 – forEach with a Dictionary

In this example, we take a Dictionary and use forEach to print (key, value) pairs.

main.swift

var myDictionary:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]

myDictionary.forEach{ item in
    print(item)
}

Output

(key: "Raghu", value: 82)
(key: "Mohan", value: 75)
(key: "John", value: 79)

Example 3 – forEach with a Set

In this example, we take a Set and use forEach to print the elements in it.

main.swift

var odds: Set = [3, 9, 7, 5]

odds.forEach{ odd in
    print(odd)
}

Output

5
7
3
9

Conclusion

In this Swift Tutorial, we have learned about forEach and how to use it with Arrays, Dictionaries, Sets, etc., with the help of Swift Example programs.