# Swift Program to Convert Array to Set

An array is used to store elements of the same data type in an order whereas a set is used to store distinct elements of the same data type without any definite order. To convert Array into set we use Set() initialiser. The resultant set contains the same elements as the original array but with no order and no duplicate elements. In this article, we will learn how to convert Array to Set using Swift programming language.

## Algorithm

• Step 1 − Create an array of integer type.

• Step 2 − Print the array.

• Step 3 − Convert array into set using Set() initializer and store the result into new variable.

• Step 4 − Print the set.

## Example 1

Following Swift program to convert array to set.

import Foundation
import Glibc

let mNumber = [30, 50, 60, 20, 80, 50, 90, 40, 30]

print("Array: ", mNumber)

// Converting array into set
let resultSet = Set(mNumber)

print("Set:", resultSet)


## Output

Array:  [30, 50, 60, 20, 80, 50, 90, 40, 30]
Set: [30, 20, 40, 60, 80, 90, 50]


Here in the above code, we have an array of integer type. Then use Set initializer to convert the given array into the set. Here, the set contain only the unique elements from the array, it remove all the duplicate elements.

## Example 2

Following Swift program to convert array to set.

import Foundation
import Glibc

let mNumber = [300, 50, 600, 20, 80, 500, 90, 40, 300]

print("Array: ", mNumber)

// Converting array into set
let resultSet = Set(mNumber.map{\$0})

print("Set:", resultSet)


## Output

Array:  [300, 50, 600, 20, 80, 500, 90, 40, 300]
Set: [40, 600, 80, 20, 90, 300, 500, 50]


Here in the above code, we have an array of integer type. Then use Set initializer to convert the given array into the set. Here we also use map() function to map each element from the array into set starting from index 0.

## Conclusion

So this is how we can convert Array to set. As we know a set contains unique elements so if an array contains duplicate elements, then the Set initializer removes those duplicate elements and stores only unique elements in the set.

Updated on: 08-Feb-2023

4K+ Views 