Set.insert() / remove() / contains()
A Swift Set is a collection of unique elements. Order is not guaranteed, and elements must conform to the Hashable protocol.
Syntax
// Declaring and initializing a Set
var set: Set<String> = ["apple", "banana", "cherry"]
var emptySet = Set<Int>() // Empty Set
var set2: Set = ["a", "b", "c"] // Type inference
// Checking if an element exists
set.contains("apple") // true
Method List
| Method / Property | Description |
|---|---|
| set.insert(_:) | Adds an element. Returns a tuple indicating whether the insertion succeeded and the inserted or existing element. |
| set.remove(_:) | Removes the specified element and returns it as an Optional. |
| set.removeAll() | Removes all elements. |
| set.contains(_:) | Returns a Bool indicating whether the element is in the set. |
| set.count | Returns the number of elements. |
| set.isEmpty | Returns a Bool indicating whether the set is empty. |
| set.update(with:) | Inserts or replaces an element, and returns the old element as an Optional if one was replaced. |
Sample Code
// Creating a Set
var fruits: Set<String> = ["apple", "banana", "cherry"]
print("Initial: \(fruits)")
// insert: Add an element (check result with the return value)
let (inserted, member) = fruits.insert("grape")
print("Insert grape: \(inserted ? "succeeded" : "already exists") - \(member)")
// Attempting to insert a duplicate
let (inserted2, _) = fruits.insert("apple")
print("Insert apple again: \(inserted2 ? "succeeded" : "already exists")")
// contains: Check if an element exists
print("banana exists: \(fruits.contains("banana"))")
print("mango exists: \(fruits.contains("mango"))")
// remove: Remove an element
if let removed = fruits.remove("banana") {
print("Removed: \(removed)")
}
print("After removal: \(fruits)")
// count / isEmpty
print("Count: \(fruits.count)")
print("Empty: \(fruits.isEmpty)")
// Iterating with for-in (order is not guaranteed)
print("List:")
for fruit in fruits.sorted() {
print(" \(fruit)")
}
Notes
A Set automatically eliminates duplicates. Even if an array contains duplicates, converting it with Set(array) removes them.
The return value of insert(_:) is a tuple of type (inserted: Bool, memberAfterInsert: Element). If the element already exists, the existing element is returned. Elements in a Set must conform to Hashable. If you use a custom type, you must add Hashable conformance.
For set operations between sets, see set.union() / intersection() / subtracting().
If you find any errors or copyright issues, please contact us.