Swift Program to Convert Set into Array

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().



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


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)


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


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: 06-Apr-2023


Kickstart Your Career

Get certified by completing the course

Get Started