Swift Program to Add Elements to a Set


In Swift, set is used to create an unordered collection of unique elements. Swift provide inbuilt functions named as formUnion() and insert() function to insert elements to a set. Lets discuss both the methods in detail along with examples.

Method 1: Using formUnion(_:) function

The formUnion(_:) function is used to insert elements of the given collection into the set.

Syntax

func formUnion(newSequence)

Where newSequence represents a collection of elements, it can be either an array or set. Also the newSequence collection must a finite collection. This function does not return any value it only add new element into the given set.

Example

In the following code, we first create a set of integer type. Then we insert new elements in the set using formUnion() function and then display the resultant set.

import Foundation
import Glibc

// Creating a set
var mySET: Set<Int> = [22, 55, 77, 88]

// Inserting new elements in the set
mySET.formUnion([11, 99, 33])

print("Updated Set:", mySET)

Output

Updated Set: [77, 33, 11, 88, 55, 22, 99]

Method 2: Using insert(_:) function

To add elements to a set we can also use insert() function. This function adds new element at the end of the set.

Syntax

func insert(element)

Where element represent the new element which we want to add in the set.This function does not return any value it only update the current set.

Example

In the following example, we first create a set of integer type. Then we insert new elements in the set individually using insert() function and then display the resultant set.

import Foundation
import Glibc

// Creating a set
var mySET: Set<Int> = [20, 60, 40, 10, 50]

// Inserting new elements in the set
mySET.insert(3)
mySET.insert(19)
mySET.insert(68)

print("Updated Set:", mySET)

Output

Updated Set: [3, 68, 20, 19, 60, 50, 10, 40]

Conclusion

So this is how we can add elements to a set. Here formUnion() function insert multiple elements at the same time whereas insert() function insert one element at a time. So the most efficient method to store multiple elements is formUnion() function. Also, don’t get confused if the order of set elements change because set is an unordered collection.

Updated on: 05-Apr-2023

235 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements