Generic Structure

Set

An unordered collection of unique elements.

Overview

You use a set instead of an array when you need to test efficiently for membership and you aren’t concerned with the order of the elements in the collection, or when you need to ensure that each element appears only once in a collection.

You can create a set with any element type that conforms to the Hashable protocol. By default, most types in the standard library are hashable, including strings, numeric and Boolean types, enumeration cases without associated values, and even sets themselves.

Swift makes it as easy to create a new set as to create a new array. Simply assign an array literal to a variable or constant with the Set type specified.

let ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]
if ingredients.contains("sugar") {
    print("No thanks, too sweet.")
}
// Prints "No thanks, too sweet."

Set Operations

Sets provide a suite of mathematical set operations. For example, you can efficiently test a set for membership of an element or check its intersection with another set:

  • Use the contains(_:) method to test whether a set contains a specific element.

  • Use the “equal to” operator (==) to test whether two sets contain the same elements.

  • Use the isSubset(of:) method to test whether a set contains all the elements of another set or sequence.

  • Use the isSuperset(of:) method to test whether all elements of a set are contained in another set or sequence.

  • Use the isStrictSubset(of:) and isStrictSuperset(of:) methods to test whether a set is a subset or superset of, but not equal to, another set.

  • Use the isDisjoint(with:) method to test whether a set has any elements in common with another set.

You can also combine, exclude, or subtract the elements of two sets:

  • Use the union(_:) method to create a new set with the elements of a set and another set or sequence.

  • Use the intersection(_:) method to create a new set with only the elements common to a set and another set or sequence.

  • Use the symmetricDifference(_:) method to create a new set with the elements that are in either a set or another set or sequence, but not in both.

  • Use the subtracting(_:) method to create a new set with the elements of a set that are not also in another set or sequence.

You can modify a set in place by using these methods’ mutating counterparts: formUnion(_:), formIntersection(_:), formSymmetricDifference(_:), and subtract(_:).

Set operations are not limited to use with other sets. Instead, you can perform set operations with another set, an array, or any other sequence type.

var primes: Set = [2, 3, 5, 7]

// Tests whether primes is a subset of a Range<Int>
print(primes.isSubset(of: 0..<10))
// Prints "true"

// Performs an intersection with an Array<Int>
let favoriteNumbers = [5, 7, 15, 21]
print(primes.intersection(favoriteNumbers))
// Prints "[5, 7]"

Sequence and Collection Operations

In addition to the Set type’s set operations, you can use any nonmutating sequence or collection methods with a set.

if primes.isEmpty {
    print("No primes!")
} else {
    print("We have \(primes.count) primes.")
}
// Prints "We have 4 primes."

let primesSum = primes.reduce(0, +)
// 'primesSum' == 17

let primeStrings = primes.sorted().map(String.init)
// 'primeStrings' == ["2", "3", "5", "7"]

You can iterate through a set’s unordered elements with a for-in loop.

for number in primes {
    print(number)
}
// Prints "5"
// Prints "7"
// Prints "2"
// Prints "3"

Many sequence and collection operations return an array or a type-erasing collection wrapper instead of a set. To restore efficient set operations, create a new set from the result.

let morePrimes = primes.union([11, 13, 17, 19])

let laterPrimes = morePrimes.filter { $0 > 10 }
// 'laterPrimes' is of type Array<Int>

let laterPrimesSet = Set(morePrimes.filter { $0 > 10 })
// 'laterPrimesSet' is of type Set<Int>

Bridging Between Set and NSSet

You can bridge between Set and NSSet using the as operator. For bridging to be possible, the Element type of a set must be a class, an @objc protocol (a protocol imported from Objective-C or marked with the @objc attribute), or a type that bridges to a Foundation type.

Bridging from Set to NSSet always takes O(1) time and space. When the set’s Element type is neither a class nor an @objc protocol, any required bridging of elements occurs at the first access of each element, so the first operation that uses the contents of the set (for example, a membership test) can take O(n).

Bridging from NSSet to Set first calls the copy(with:) method (- copyWithZone: in Objective-C) on the set to get an immutable copy and then performs additional Swift bookkeeping work that takes O(1) time. For instances of NSSet that are already immutable, copy(with:) returns the same set in constant time; otherwise, the copying performance is unspecified. The instances of NSSet and Set share buffer using the same copy-on-write optimization that is used when two instances of Set share buffer.

Nested Types

Set.Index

Used to access the members in an instance of Set<Element>.

Symbols

Initializers

init()

Creates an empty set.

init<Source>(Source)

Creates a new set from a finite sequence of items.

init<S>(S)

Creates a new set from a finite sequence of items.

init(arrayLiteral: Element...)

Creates a set containing the elements of the given array literal.

init(arrayLiteral: (Element)...)

Creates a set containing the elements of the given array literal.

init(minimumCapacity: Int)

Creates a new, empty set with at least the specified number of elements’ worth of buffer.

Instance Properties

var count: Int

The number of elements in the set.

var count: Int

The number of elements in the collection.

var customMirror: Mirror

A mirror that reflects the set.

var debugDescription: String

A string that represents the contents of the set, suitable for debugging.

var description: String

A string that represents the contents of the set.

var endIndex: Set<Element>.Index

The “past the end” position for the set—that is, the position one greater than the last valid subscript argument.

var first: Element?

The first element of the set.

var first: Element?

The first element of the collection.

var hashValue: Int

The hash value for the set.

var indices: DefaultIndices<Set<Element>>

The indices that are valid for subscripting the collection, in ascending order.

var isEmpty: Bool

A Boolean value that indicates whether the set is empty.

var isEmpty: Bool

A Boolean value that indicates whether the set has no elements.

var isEmpty: Bool

A Boolean value indicating whether the collection is empty.

var lazy: LazySequence<Set<Element>>

A sequence containing the same elements as this sequence, but on which some operations, such as map and filter, are implemented lazily.

var lazy: LazyCollection<Set<Element>>

A view onto this collection that provides lazy implementations of normally eager operations, such as map and filter.

var startIndex: Set<Element>.Index

The starting position for iterating members of the set.

var underestimatedCount: Int

Returns a value less than or equal to the number of elements in the sequence, nondestructively.

var underestimatedCount: Int

A value less than or equal to the number of elements in the collection.

Instance Methods

func contains(Element)

Returns a Boolean value that indicates whether the given element exists in the set.

func contains(where: (Element) -> Bool)

Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate.

func drop(while: (Element) -> Bool)

Returns a subsequence by skipping elements while predicate returns true and returning the remaining elements.

func dropFirst()

Returns a subsequence containing all but the first element of the sequence.

func dropFirst(Int)

Returns a subsequence containing all but the given number of initial elements.

func dropLast()

Returns a subsequence containing all but the last element of the sequence.

func dropLast(Int)

Returns a subsequence containing all but the specified number of final elements.

func elementsEqual<OtherSequence>(OtherSequence)

Returns a Boolean value indicating whether this sequence and another sequence contain the same elements in the same order.

func elementsEqual<OtherSequence>(OtherSequence, by: (Element, Element) -> Bool)

Returns a Boolean value indicating whether this sequence and another sequence contain equivalent elements, using the given predicate as the equivalence test.

func enumerated()

Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero, and x represents an element of the sequence.

func filter((Element) -> Bool)

Returns an array containing, in order, the elements of the sequence that satisfy the given predicate.

func first(where: (Element) -> Bool)

Returns the first element of the sequence that satisfies the given predicate.

func flatMap<ElementOfResult>((Element) -> ElementOfResult?)

Returns an array containing the non-nil results of calling the given transformation with each element of this sequence.

func flatMap<SegmentOfResult>((Element) -> SegmentOfResult)

Returns an array containing the concatenated results of calling the given transformation with each element of this sequence.

func forEach((Element) -> Void)

Calls the given closure on each element in the sequence in the same order as a for-in loop.

func formIntersection<S>(S)

Removes the elements of the set that aren’t also in the given sequence.

func formSymmetricDifference(Set<Set.Element>)

Removes the elements of the set that are also in the given sequence and adds the members of the sequence that are not already in the set.

func formSymmetricDifference<S>(S)

Replace this set with the elements contained in this set or the given set, but not both.

func formUnion<S>(S)

Inserts the elements of the given sequence into the set.

func index(after: Set<Element>.Index)
func index(of: Set.Element)

Returns the index of the given element in the set, or nil if the element is not a member of the set.

func index(where: (Element) -> Bool)

Returns the first index in which an element of the collection satisfies the given predicate.

func insert(Element)

Inserts the given element in the set if it is not already present.

func insert<ConcreteElement>(ConcreteElement)
func intersection(Set<Set.Element>)

Returns a new set with the elements that are common to both this set and the given sequence.

func intersection<S>(S)

Returns a new set with the elements that are common to both this set and the given sequence.

func isDisjoint(with: Set<Set.Element>)

Returns a Boolean value that indicates whether this set has no members in common with the given set.

func isDisjoint<S>(with: S)

Returns a Boolean value that indicates whether the set has no members in common with the given sequence.

func isStrictSubset(of: Set<Set.Element>)

Returns a Boolean value that indicates whether the set is a strict subset of the given sequence.

func isStrictSubset<S>(of: S)

Returns a Boolean value that indicates whether the set is a strict subset of the given sequence.

func isStrictSuperset(of: Set<Set.Element>)

Returns a Boolean value that indicates whether the set is a strict superset of the given sequence.

func isStrictSuperset<S>(of: S)

Returns a Boolean value that indicates whether the set is a strict superset of the given sequence.

func isSubset(of: Set<Set.Element>)

Returns a Boolean value that indicates whether this set is a subset of the given set.

func isSubset<S>(of: S)

Returns a Boolean value that indicates whether the set is a subset of the given sequence.

func isSuperset(of: Set<Set.Element>)

Returns a Boolean value that indicates whether this set is a superset of the given set.

func isSuperset<S>(of: S)

Returns a Boolean value that indicates whether the set is a superset of the given sequence.

func joined()

Returns the elements of this sequence of sequences, concatenated.

func joined()

Returns the elements of this collection of collections, concatenated.

func joined<Separator>(separator: Separator)

Returns the concatenated elements of this sequence of sequences, inserting the given separator between each element.

func joined(separator: String)

Returns a new string by concatenating the elements of the sequence, adding the given separator between each element.

func lexicographicallyPrecedes<OtherSequence>(OtherSequence)

Returns a Boolean value indicating whether the sequence precedes another sequence in a lexicographical (dictionary) ordering, using the less-than operator (<) to compare elements.

func lexicographicallyPrecedes<OtherSequence>(OtherSequence, by: (Element, Element) -> Bool)

Returns a Boolean value indicating whether the sequence precedes another sequence in a lexicographical (dictionary) ordering, using the given predicate to compare elements.

func makeIterator()

Returns an iterator over the members of the set.

func map<T>((Element) -> T)

Returns an array containing the results of mapping the given closure over the sequence’s elements.

func map<T>((Element) -> T)

Returns an array containing the results of mapping the given closure over the sequence’s elements.

func max()

Returns the maximum element in the sequence.

func max(by: (Element, Element) -> Bool)

Returns the maximum element in the sequence, using the given predicate as the comparison between elements.

func min()

Returns the minimum element in the sequence.

func min(by: (Element, Element) -> Bool)

Returns the minimum element in the sequence, using the given predicate as the comparison between elements.

func popFirst()

Removes and returns the first element of the set.

func prefix(Int)

Returns a subsequence, up to the specified maximum length, containing the initial elements of the collection.

func prefix(through: Set<Element>.Index)

Returns a subsequence from the start of the collection through the specified position.

func prefix(upTo: Set<Element>.Index)

Returns a subsequence from the start of the collection up to, but not including, the specified position.

func prefix(while: (Element) -> Bool)

Returns a subsequence containing the initial elements until predicate returns false and skipping the remaining elements.

func reduce<Result>(Result, (Result, Element) -> Result)

Returns the result of combining the elements of the sequence using the given closure.

func remove(Element)

Removes the specified element from the set.

func remove<ConcreteElement>(ConcreteElement)
func remove(at: Set<Element>.Index)

Removes the element at the given index of the set.

func removeAll(keepingCapacity: Bool)

Removes all members from the set.

func removeFirst()

Removes the first element of the set.

func reversed()

Returns an array containing the elements of this sequence in reverse order.

func sorted()

Returns the elements of the sequence, sorted.

func sorted(by: (Element, Element) -> Bool)

Returns the elements of the sequence, sorted using the given predicate as the comparison between elements.

func split(maxSplits: Int, omittingEmptySubsequences: Bool, whereSeparator: (Element) -> Bool)

Returns the longest possible subsequences of the collection, in order, that don’t contain elements satisfying the given predicate.

func split(separator: Element, maxSplits: Int, omittingEmptySubsequences: Bool)

Returns the longest possible subsequences of the collection, in order, around elements equal to the given element.

func starts<PossiblePrefix>(with: PossiblePrefix)

Returns a Boolean value indicating whether the initial elements of the sequence are the same as the elements in another sequence.

func starts<PossiblePrefix>(with: PossiblePrefix, by: (Element, Element) -> Bool)

Returns a Boolean value indicating whether the initial elements of the sequence are equivalent to the elements in another sequence, using the given predicate as the equivalence test.

func subtract(Set<Set.Element>)

Removes the elements of the given set from this set.

func subtract(Set<Element>)

Removes the elements of the given set from this set.

func subtract<S>(S)

Removes the elements of the given sequence from the set.

func subtracting(Set<Set.Element>)

Returns a new set containing the elements of this set that do not occur in the given set.

func subtracting<S>(S)

Returns a new set containing the elements of this set that do not occur in the given sequence.

func suffix(Int)

Returns a subsequence, up to the given maximum length, containing the final elements of the collection.

func suffix(from: Set<Element>.Index)

Returns a subsequence from the specified position to the end of the collection.

func symmetricDifference<S>(S)

Returns a new set with the elements that are either in this set or in the given sequence, but not in both.

func union<S>(S)

Returns a new set with the elements of both this set and the given sequence.

func update(with: Element)

Inserts the given element into the set unconditionally.

func update<ConcreteElement>(with: ConcreteElement)

Subscripts

subscript(Set<Element>.Index)

Accesses the member at the given position.

subscript(Range<Set<Element>.Index>)

Accesses a contiguous subrange of the collection’s elements.

Operator Functions

static func ==(Set<Element>, Set<Element>)

Returns a Boolean value indicating whether two sets have equal elements.

See Also

Related Symbols

Hashable