Convert Set into Array in Swift



In Swift, a set is used to define an unordered collection of unique elements whereas an array is used to define an ordered collection with may or may not be unique elements. To convert a set into an array Swift provides an inbuilt initializer named as Array().

Syntax

Array(MySet)

Where Array() initializer takes only one parameter that is the name of the set and, returns an array of the same type.

Example

In the following example, we will create and initialize a set of strings. Then convert the set into the array using Array() initializer and then display the output.

import Foundation
import Glibc

// Creating a set of string
var myFavfruit : Set = ["Orange", "Sweet apple", "Apple", "Kiwi", "Mango", "Jackfruit"] 

// Converting a set into array
var resArray = Array(myFavfruit)

print("Array: ", resArray)

Output

Array:  ["Mango", "Orange", "Kiwi", "Jackfruit", "Sweet apple", "Apple"]

Conclusion

Therefore, this is how we can convert a set into an array. However, it is not necessary that the order of the elements in the resultant array is the same as the original set because sets are the unordered collection.

Updated on: 2023-04-06T08:38:24+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements