Swift
Programming
Set to Array
Code Conversion
Swift Language

Convert a Set to an Array in Swift

Codemia Knowledge Hub ·

To convert a Set to an Array in Swift, pass the set to the Array initializer: Array(mySet). The array contains every element of the set, but its order is not defined, so call sorted() if you need a specific order.

swift
let mySet: Set<Int> = [1, 2, 3, 4, 5]
let myArray: [Int] = Array(mySet)

How Set and Array differ

Converting between the two is useful when you want the strengths of both: the uniqueness guarantee of a set and the ordering and flexibility of an array.

A Set is an unordered collection of unique items. Its defining feature is that it cannot contain duplicate elements, which makes it a good fit for membership tests and for deduplicating data.

swift
var mySet: Set<String> = ["Apple", "Banana", "Cherry"]

An Array is an ordered collection that can contain duplicate elements. It is one of the most widely used data structures because of its flexibility and ease of use.

swift
var myArray: [String] = ["Apple", "Banana", "Banana", "Cherry"]
FeatureSetArray
OrderUnorderedOrdered
Unique ElementsYesNo
Duplicates AllowedNoYes
Main PurposeMembership tests, unique element storageOrdered collection with duplicates
Conversion to ArrayArray(set)N/A
Typical Time Complexity (conversion to Array)O(n)N/A
Sorting AvailableMust convert to Array firstYes

Getting a predictable order

Because the order after conversion is undefined, sort the array explicitly when order matters:

swift
let sortedArray = myArray.sorted()

A complete example:

swift
1// Define a Set of numbers
2let numberSet: Set = [9, 3, 1, 5, 7]
3
4// Convert the Set to an Array
5let numberArray = Array(numberSet)
6
7// Sort the Array
8let sortedNumberArray = numberArray.sorted()
9
10// Display results
11print("Original Set: \(numberSet)")
12print("Converted Array: \(numberArray)")
13print("Sorted Array: \(sortedNumberArray)")

Cost of the conversion

Converting a Set to an Array is typically an O(n) operation, where n is the number of elements in the set. The cost comes from iterating through the set once to build the array. If you also sort the result, that adds O(n log n).

When to convert

  • Deduplication: put the elements in a Set to remove duplicates, then convert back to an Array.
  • Order-specific work: sort or rearrange elements once uniqueness is guaranteed.

Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms