How to initialize a set with a range in Swift
Overview
A set is a sequence or collection of unique elements. These elements can never be duplicated. A range is a sequence that contains values from a lower bound and upper bound. We can initialize a set using a range in Swift.
Syntax
let set = Set(range)
Initialising a Set with a Range in Swift
Parameter
range: This is the range by which the set instance will be initialized.
Return value
A set is returned and initialized with values from the given range.
Code
// create Set instances and initialiselet set1 = Set(0..<7) // range from 0-6let set2 = Set(10..<20) // range from 10-20let set3 = Set(0..<0) // empty range// print Set instancesprint(set1)print(set2)print(set3)
Explanation
- Line 2–4: We create some
Setinstances and initialize them with some range sequences. - Line 7–9: We print the sets.