In Swift, sets are value types, so when you assign a set to another variable, you create a copy of the set by default.
In this example,
numbers
containing some integer elements.numbers
to a new variable named copiedNumbers
.copiedNumbers
contains a copy of all elements from numbers
.let numbers: Set<Int> = [1, 2, 3, 4, 5]
let copiedNumbers = numbers
print("Copied Numbers:")
for number in copiedNumbers {
print(number)
}
Copied Numbers: 1 2 3 4 5
In this example,
fruits
containing some string elements.fruits
to a new variable named copiedFruits
.copiedFruits
contains a copy of all elements from fruits
.let fruits: Set<String> = ["Apple", "Banana", "Cherry", "Date"]
let copiedFruits = fruits
print("Copied Fruits:")
for fruit in copiedFruits {
print(fruit)
}
Copied Fruits: Banana Apple Cherry Date
In this tutorial, we learned How to Copy a Set in Swift language with well detailed examples.