Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Swift Dictionary

  1. Home
  2. Swift Dictionary
  3. Set.insert() / remove() / contains()

Set.insert() / remove() / contains()

Since: Swift 1.0(2014)

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> = ["item_a", "item_b", "item_c"]
var emptySet = Set<Int>() // Empty Set
var set2: Set = ["a", "b", "c"] // Type inference

// Checking if an element exists
set.contains("item_a") // true

Method List

Method / PropertyDescription
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.countReturns the number of elements.
set.isEmptyReturns 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

sample_set_insert_remove.swift
// Creating a Set
var members: Set<String> = ["item_a", "item_b", "item_c"]
print("Initial: \(members)")

// insert: Add an element (check result with the return value)
let (inserted, member) = members.insert("item_d")
print("Insert item_d: \(inserted ? "succeeded" : "already exists") - \(member)")

// Attempting to insert a duplicate
let (inserted2, _) = members.insert("item_a")
print("Insert item_a again: \(inserted2 ? "succeeded" : "already exists")")

// contains: Check if an element exists
print("item_b exists: \(members.contains("item_b"))")
print("item_e exists: \(members.contains("item_e"))")

// remove: Remove an element
if let removed = members.remove("item_b") {
    print("Removed: \(removed)")
}
print("After removal: \(members)")

// count / isEmpty
print("Count: \(members.count)")
print("Empty: \(members.isEmpty)")

// Iterating with for-in (order is not guaranteed)
print("List:")
for member in members.sorted() {
    print("  \(member)")
}

Running the above produces the following output:

swift sample_set_insert_remove.swift
Initial: ["item_a", "item_b", "item_c"]
Insert item_d: succeeded - item_d
Insert item_a again: already exists
item_b exists: true
item_e exists: false
Removed: item_b
After removal: ["item_a", "item_c", "item_d"]
Count: 3
Empty: false
List:
  item_a
  item_c
  item_d

Because a Set does not guarantee element order, the output of print("Initial: \(members)") and print("After removal: \(members)") may appear in a different order on each run.

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 .