In Swift, you can add an item to a Set using the insert() method.
In this example,
numbers
containing some integer elements.numbers
to add a new integer element, such as 6
, to the set.numbers
contains the added element 6
.var numbers: Set<Int> = [1, 2, 3, 4, 5]
numbers.insert(6)
print("Numbers: \(numbers)")
Numbers: [3, 4, 5, 6, 1, 2]
In this example,
fruits
containing some string elements.fruits
to add a new string element, such as "Orange"
, to the set.fruits
contains the added element "Orange"
.var fruits: Set<String> = ["Apple", "Banana", "Cherry"]
fruits.insert("Orange")
print("Fruits: \(fruits)")
Fruits: ["Banana", "Cherry", "Orange", "Apple"]
In this tutorial, we learned How to add an Item to a Set in Swift language with well detailed examples.