Swift – Add an Element to a Set
Use the Swift Set.insert(_:) method to add an element to a set. A set stores only unique values, so inserting an element that is already present does not create a duplicate.
To insert an element to a Set, use insert() method. The syntax is:
setName.insert(element)
The set must be declared with var because inserting an element changes the collection. The inserted value must have the same type as the other elements in the set.
How Swift Set insert(_:) Handles New and Existing Values
The insert(_:) method behaves differently depending on whether the value is already in the set:
- If the value is not present, Swift adds it to the set.
- If the value is already present, the set remains unchanged.
- No error is thrown when a duplicate value is inserted.
- The method returns information indicating whether an insertion occurred.
Example 1 – Insert a New Element into a Swift Set
In this example, we will take a Set containing some prime numbers. We will add a new element that is not already present.
main.swift
var primes: Set = [2, 3, 5, 7, 11, 13]
primes.insert(17)
for prime in primes {
print(prime)
}
Output
17
2
5
7
3
11
13
The new element is added to the Set.
A set does not guarantee a fixed iteration order. Therefore, the values may appear in a different order when you run the program, but the set will still contain the same elements.
Example 2 – Insert a Duplicate Element into a Swift Set
In this example, we will take a Set containing some prime numbers. We will add an element that is already present and see what happens.
main.swift
var primes: Set = [2, 3, 5, 7, 11, 13]
primes.insert(11)
for prime in primes {
print(prime)
}
Output
5
7
2
3
11
13
If an element is already present, the insert() method does not throw any error or warning. It does ignore the insert and the Set remains unchanged.
Check Whether Swift Set insert(_:) Added the Element
The insert(_:) method returns a named tuple containing inserted and memberAfterInsert. The inserted value is true only when the element was newly added.
var languages: Set<String> = ["Swift", "Kotlin"]
let firstResult = languages.insert("Python")
print(firstResult.inserted)
print(firstResult.memberAfterInsert)
let secondResult = languages.insert("Swift")
print(secondResult.inserted)
print(secondResult.memberAfterInsert)
Output
true
Python
false
Swift
The first insertion adds "Python", so inserted is true. The second insertion finds that "Swift" is already present, so inserted is false.
Use the inserted Result in a Swift if Statement
You can use the returned inserted value when later logic should run only for a newly added element.
var registeredEmails: Set<String> = ["maya@example.com"]
let email = "arun@example.com"
if registeredEmails.insert(email).inserted {
print("Email added")
} else {
print("Email already exists")
}
Output
Email added
Insert Multiple Elements into a Swift Set
The insert(_:) method adds one element at a time. To add multiple values, use formUnion(_:) or insert the values in a loop.
Add Multiple Set Elements with formUnion(_:)
The mutating formUnion(_:) method adds all unique values from another sequence to the existing set.
var numbers: Set<Int> = [1, 2, 3]
let additionalNumbers = [3, 4, 5, 6]
numbers.formUnion(additionalNumbers)
print(numbers.sorted())
Output
[1, 2, 3, 4, 5, 6]
The value 3 was already present, so it appears only once. The call to sorted() is used only to produce predictable output; it returns an array and does not change the set’s unordered nature.
Insert Array Elements into a Swift Set with a Loop
A loop is useful when you need to inspect the result of each individual insertion.
var fruits: Set<String> = ["Apple", "Mango"]
let newFruits = ["Mango", "Orange", "Banana"]
for fruit in newFruits {
let result = fruits.insert(fruit)
print("\(fruit): \(result.inserted)")
}
Output
Mango: false
Orange: true
Banana: true
Create a New Swift Set by Combining Existing Values
Use union(_:) when you want a new set containing values from both collections without modifying the original set.
let primaryColors: Set<String> = ["Red", "Blue", "Yellow"]
let extraColors: Set<String> = ["Green", "Blue"]
let allColors = primaryColors.union(extraColors)
print(allColors.sorted())
print(primaryColors.sorted())
Output
["Blue", "Green", "Red", "Yellow"]
["Blue", "Red", "Yellow"]
The original primaryColors set remains unchanged. In comparison, formUnion(_:) modifies the set on which it is called.
Why insert(_:) Cannot Be Used on a let Set
A set declared with let is immutable. Swift does not allow elements to be inserted into or removed from it.
let fixedNumbers: Set<Int> = [1, 2, 3]
// fixedNumbers.insert(4) // Compile-time error
Declare the set with var when its contents need to change:
var editableNumbers: Set<Int> = [1, 2, 3]
editableNumbers.insert(4)
print(editableNumbers.contains(4))
Output
true
Swift Set insert(_:) Compared with Array append(_:)
Sets and arrays use different methods because they represent different kinds of collections.
| Operation | Swift Set | Swift Array |
|---|---|---|
| Add one element | insert(_:) | append(_:) |
| Add multiple elements | formUnion(_:) | append(contentsOf:) |
| Allows duplicates | No | Yes |
| Preserves insertion order | No guaranteed order | Yes |
Use a set when values must be unique and order is not important. Use an array when order or duplicate values must be preserved.
Common Swift Set Insertion Mistakes
- Declaring the set with let: Use
varwhen you need to insert values. - Expecting duplicate elements: A set keeps only one instance of each equal value.
- Expecting insertion order: Swift sets do not guarantee that elements will be printed in the order they were inserted.
- Using append(_:): Sets use
insert(_:);append(_:)is used with arrays. - Ignoring the insert result: Check
.insertedwhen your program must know whether the value was newly added.
Frequently Asked Questions About Adding Values to a Swift Set
How do I add one element to a Swift Set?
Declare the set with var and call setName.insert(value).
What happens if I insert a duplicate value into a Swift Set?
The set remains unchanged because sets store unique values. The returned inserted property is false.
How do I insert an array into a Swift Set?
Call set.formUnion(array) to add all unique array elements, or loop over the array and call insert(_:) for each value.
Can I append an element to a Swift Set?
No append(_:) method is used for sets. Use insert(_:). The term append implies an ordered end position, while a set has no guaranteed element order.
How can I tell whether a Swift Set insertion succeeded?
Read the inserted property returned by insert(_:). It is true for a new value and false for an existing value.
Editorial QA Checklist for Swift Set insert(_:) Examples
- Confirm every set that is modified is declared with
var. - Verify inserted values use the same element type as the set.
- Do not describe set output order as fixed or predictable.
- Check that duplicate insertions leave the set count unchanged.
- Use
insert(_:)for one value andformUnion(_:)for multiple values where appropriate.
Swift Set Insertion Summary
Use insert(_:) to add one value to a mutable Swift set. Check the returned inserted property when you need to know whether the value was new. For multiple values, use formUnion(_:) to modify the existing set or union(_:) to create a new combined set.
In this Swift Tutorial, we have learned how to insert an element into a Set with the help of Swift Example programs.
TutorialKart.com