How to Convert a Swift Set to an Array

How to Convert a Swift Set to an Array

Written by

in

Quick answer: Use Array(yourSet) to convert a Swift Set to an Array. Set conforms to Sequence, so the Array initializer can consume it directly without bridging to NSSet. Use sorted(), map, or filter if you need ordering or transformation during the conversion.

Why this happens

If you came from Objective-C, you expect allObjects() to turn a set into an array. NSSet has that method, and bridging a Swift Set to NSSet just to call it does compile, but it is unnecessary and adds overhead.

Swift’s Set is a separate value type. It does not have allObjects(). Instead, it conforms to Sequence and Collection. Any type that is a Sequence can be used to initialize an Array with Array(_:). That is the idiomatic way to get an array from a set, and it has worked since Set was introduced in Swift 1.2.

Because a Set is unordered, the resulting array has no guaranteed order. If you need a stable order for UI, tests, or persistence, you must sort or otherwise order the elements explicitly.

How to fix it

All examples below assume Swift 5+. No extra imports are needed for the core conversion. Import Foundation only if you are also working with NSSet.

1. Use the Array initializer — Array(set)

This is the direct replacement for allObjects() and the solution you should reach for first.

let mySet: Set<String> = ["a", "b", "a"]
// Set removes duplicates, so mySet contains "a" and "b"
let myArray = Array(mySet) // Array<String>
print(myArray) // e.g. ["b", "a"] - order is not defined

Why it works:

// Array has this initializer:
// init<S>(_ s: S) where S : Sequence, Element == S.Element
// Set conforms to Sequence, so you can pass it directly.
let stringSet = Set(["car", "boat", "bike", "toy"])
let stringArray = Array(stringSet)
print(stringArray) // e.g. ["toy", "car", "bike", "boat"]

Use this when you just need the elements in an array and you do not care about order. It is O(n), creates a new array, and does not bridge to Objective-C.

If the compiler cannot infer the type, annotate it:

let intSet: Set<Int> = [1, 2, 3]
let intArray: [Int] = Array(intSet)

2. Get a deterministic order with sorted()

If you need the array to be predictable — for example to display in a List or to compare in unit tests — sort the set while converting.

let stringSet = Set(["car", "boat", "bike", "toy"])
let sortedArray = stringSet.sorted() // Array<String>
print(sortedArray) // ["bike", "boat", "car", "toy"]

sorted() returns an Array already, so you do not need to wrap it in Array(...). For custom types, provide a comparator:

struct User: Hashable, Comparable {
    let id: Int
    let name: String
    static func < (lhs: User, rhs: User) -> Bool { lhs.name < rhs.name }
}

let users: Set<User> = [User(id: 2, name: "Maya"), User(id: 1, name: "Alex")]
let ordered = users.sorted() // sorted by <
let orderedByID = users.sorted { $0.id < $1.id }

Use sorted() whenever order matters. Do not rely on the order of Array(set).

3. Transform or filter while converting

Because Set is a Collection, you can chain functional methods and get an array back. This avoids creating an intermediate array first.

Filter to exclude elements:

let stringSet = Set(["car", "boat", "bike", "toy"])
let filtered = stringSet.filter { !$0.hasPrefix("b") }
print(filtered) // e.g. ["car", "toy"] - Array<String>

Note: filter on a Set returns an Array, not a Set.

Map to transform elements:

let intSet: Set<Int> = [1, 3, 5, 2]
let stringArray = intSet.map { String($0) } // Array<String>
print(stringArray) // e.g. ["5", "2", "3", "1"]

// If you just want the same values as an array, map does the same as Array(_:)
let intArray = intSet.map { $0 } // Array<Int>
// Prefer Array(intSet) for that case - it is clearer

Compact map to drop nils:

The older flatMap for this purpose is now compactMap in modern Swift:

let raw: Set<String> = ["1", "a", "3"]
let numbers = raw.compactMap { Int($0) } // Array<Int> = [1, 3] in some order

Choose the method that matches your intent:

  • Array(set) — no transformation, just type conversion.
  • sorted() — conversion + deterministic order.
  • filter / map / compactMap — conversion + transformation in one pass.

4. Avoid bridging to NSSet unless you need Objective-C interop

You can still do this, but you should not for pure Swift code:

import Foundation

let swiftSet: Set<String> = ["a", "b"]
let nsSet = swiftSet as NSSet
let bridgedArray = nsSet.allObjects as! [String]

This bridges every element to an Objective-C object, goes through NSSet, and then force-casts back. It is longer, harder to read, and can be slower. Only use it when an API specifically requires NSSet or allObjects.

If you have an NSSet from an older API (for example Core Data), convert the other way:

let nsSet: NSSet = NSSet(array: ["a", "b"])
let swiftArray = (nsSet as Set<String>).sorted()
// or if you know the type:
let array2 = nsSet.allObjects as! [String]

How to prevent it

  • Always use Array(set) or set.sorted() instead of bridging to NSSet for Swift-only code.
  • Treat any array created from a set as unordered unless you explicitly sorted it. Do not write tests that assert a specific order from Array(set).
  • Annotate the array type when the compiler cannot infer it, rather than casting through Any or NSObject.
  • When you need to transform, prefer chaining map/filter/compactMap/sorted directly on the set instead of creating an intermediate array first.
  • If you work with NSSet from Objective-C frameworks, convert to Set<Element> once at the boundary, then stay in Swift types.

FAQ

Does Array(set) keep the order of elements?

No. Set is unordered by definition, so Array(set) returns elements in an unspecified order that can change between runs. If you need stability, use set.sorted() or set.sorted(by:).

Is Array(set) faster than (set as NSSet).allObjects?

Yes for Swift code. Array(set) copies the elements directly without Objective-C bridging. Bridging to NSSet adds extra allocation and type casting and should only be used when you must interoperate with an Objective-C API that expects NSSet.

Should I use map or compactMap on a Set?

Use map when the transform never returns nil and you want a one-to-one result. Use compactMap when the transform is failable (like Int(_:) or URL(string:)) and you want to drop nil results. Both return an Array, not a Set.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.