How to insert a value to a set in Swift

Overview

The insert() method inserts a value or an element to a set in Swift.

Syntax

set.insert(element)

Parameters

element: This is the element we want to insert into the set.

Return value

It returns a boolean value and also the element we want to insert. The boolean denotes if the insertion was successful.

Example

// create some sets
var evenNumbers : Set = [10, 2, 6, 8, 4]
var oddNumbers : Set = [11, 5, 7, 3, 9]
var first_names : Set = ["john", "jane", "henry", "mark"]
// insert some elements and store results
let ins1 = evenNumbers.insert(45)
let ins2 = oddNumbers.insert(13)
let ins3 = first_names.insert("Theodore")
let ins4 = first_names.insert("")
// print inserted results
print(ins1)
print(ins2)
print(ins3)
print(ins4)
// print sets
print(evenNumbers)
print(oddNumbers)
print(first_names)

Explanation

  • Line 2–4: We create some sets.
  • Line 7–10: We use the insert() method to insert some elements into the sets. We also store the returned results into some variables.
  • Line 13–16: We print the returned results.
  • Line 19–21: We print the sets and notice that the elements have been inserted.

Free Resources