Sahil Kapoor Sahil Kapoor - 20 days ago 5
Swift Question

How to convert Range<Int> to Set<Int>?

I want to convert a

Range
of
Int
to a
Set<Int>
like this

[0..<count]
->
Set[1,2,3..count]
.

Answer

A (countable) range is a sequence, and Set has an initializer

public init<Source : Sequence where Source.Iterator.Element == Element>(_ sequence: Source)

which allows to create a set from a sequence directly:

let count = 10
let range = 0..<count // CountableRange<Int>
let set = Set(range)  // Set<Int>

Or just

let count = 10
let set = Set(0..<count) // Set<Int>

Or

let set = Set(0..<10)  // Set<Int>

Note that there is also IndexSet which is a dedicated type to manage sets of (non-negative) integer values:

let indexSet = IndexSet(0..<10)
Comments