Swift Set to Array
You can create an array with all elements from a given Swift Set
simply with
let array = Array(someSet)
This works because Set
conforms to the SequenceType
protocoland an Array
can be initialized with a sequence. Example:
let mySet = Set(["a", "b", "a"]) // Set<String>let myArray = Array(mySet) // Array<String>print(myArray) // [b, a]
In the simplest case, with Swift 3, you can use Array
's init(_:)
initializer to get an Array
from a Set
. init(_:)
has the following declaration:
init<S>(_ s: S) where S : Sequence, Element == S.Iterator.Element
Creates an array containing the elements of a sequence.
Usage:
let stringSet = Set(arrayLiteral: "car", "boat", "car", "bike", "toy") let stringArray = Array(stringSet)print(stringArray)// may print ["toy", "car", "bike", "boat"]
However, if you also want to perform some operations on each element of your Set
while transforming it into an Array
, you can use map
, flatMap
, sort
, filter
and other functional methods provided by Collection
protocol:
let stringSet = Set(["car", "boat", "bike", "toy"])let stringArray = stringSet.sorted()print(stringArray)// will print ["bike", "boat", "car", "toy"]
let stringSet = Set(arrayLiteral: "car", "boat", "car", "bike", "toy") let stringArray = stringSet.filter { $0.characters.first != "b" }print(stringArray)// may print ["car", "toy"]
let intSet = Set([1, 3, 5, 2]) let stringArray = intSet.flatMap { String($0) }print(stringArray)// may print ["5", "2", "3", "1"]
let intSet = Set([1, 3, 5, 2])// alternative to `let intArray = Array(intSet)`let intArray = intSet.map { $0 }print(intArray)// may print [5, 2, 3, 1]
I created a simple extension that gives you an unsorted Array
as a property of Set
in Swift 4.0.
extension Set { var array: [Element] { return Array(self) }}
If you want a sorted array, you can either add an additional computed property, or modify the existing one to suit your needs.
To use this, just call
let array = set.array