Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
set
communitycreator

How to initialize a set with a range in Swift

Theodore Kelechukwu Onyejiaku

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 initialise
let set1 = Set(0..<7)    // range from 0-6
let set2 = Set(10..<20)  // range from 10-20
let set3 = Set(0..<0)    // empty range

// print Set instances
print(set1)
print(set2)
print(set3)
Initialize a set with a range sequence

Explanation

  • Line 2–4: We create some Set instances and initialize them with some range sequences.
  • Line 7–9: We print the sets.

RELATED TAGS

swift
set
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring