Swift – Add Element to Set

In this tutorial, we will learn how to add, append or insert an element to a Set in Swift programming.

To insert an element to a Set, use insert() method. The syntax is:

</>
Copy
setName.insert(element)

Example 1 – Add / Insert / Append a new Element to Set

In this example, we will take a Set containing some prime numbers. We will add a new element that is not already present.

main.swift

</>
Copy
var primes: Set = [2, 3, 5, 7, 11, 13]

primes.insert(17)

for prime in primes {
    print(prime)
}

Output

17
2
5
7
3
11
13

The new element is added to the Set.

Example 2 – Add / Insert / Append a new Element to Set

In this example, we will take a Set containing some prime numbers. We will add an element that is already present and see what happens.

main.swift

</>
Copy
var primes: Set = [2, 3, 5, 7, 11, 13]

primes.insert(11)

for prime in primes {
    print(prime)
}

Output

5
7
2
3
11
13

If an element is already present, the insert() method does not throw any error or warning. It does ignore the insert and the Set remains unchanged.

Conclusion

In this Swift Tutorial, we have learned how to insert an element into a Set with the help of Swift Example programs.