Swift – Iterate over Set

To iterate over the values of a Set in Swift, we can use for-in loop statement.

The syntax to iterate over Set using for-in is

</>
Copy
for value in set {
    //code
}

Examples

In the following program, we will take a Set of numbers nums, and iterate over these values using for-in statement.

main.swift

</>
Copy
var nums: Set = [1, 4, 9]
for value in nums {
    print(value)
}

Output

Swift - Iterate over Set - Example

Now, let us take a set of Strings names, and iterate over its values.

main.swift

</>
Copy
var names: Set = ["ABC", "XYM", "PQR"]
for value in names {
    print(value)
}

Output

Swift - Iterate over Set - Example

Conclusion

In this Swift Tutorial, we learned how to iterate over values of a Set using for-in loop statement.