<!--
{
  "availability" : [
    "iOS: 8.0.0 -",
    "iPadOS: 8.0.0 -",
    "macCatalyst: 13.0.0 -",
    "macOS: 10.10.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Swift",
  "identifier" : "/documentation/Swift/Set",
  "metadataVersion" : "0.1.0",
  "role" : "Structure",
  "symbol" : {
    "kind" : "Structure",
    "modules" : [
      "Swift"
    ],
    "preciseIdentifier" : "s:Sh"
  },
  "title" : "Set"
}
-->

# Set

An unordered collection of unique elements.

```
@frozen struct Set<Element> where Element : Hashable
```

## 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 primesStrings = primes.map(String.init)
// 'primesStrings' is of type Array<String>
let primesStringsSet = Set(primes.map(String.init))
// 'primesStringsSet' is of type Set<String>
```

# 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.

## Topics

### Creating a Set

In addition to using an array literal, you can also create a set using these initializers.

[`init()`](/documentation/Swift/Set/init())

Creates an empty set.

[`init(minimumCapacity: Int)`](/documentation/Swift/Set/init(minimumCapacity:))

Creates an empty set with preallocated space for at least the specified
number of elements.

[`init<S>(S)`](/documentation/Swift/Set/init(_:)-9cgks)

Creates a new set from a finite sequence of items.

[`init<Source>(Source)`](/documentation/Swift/Set/init(_:))

Creates a new set from a finite sequence of items.

### Inspecting a Set

[`var isEmpty: Bool`](/documentation/Swift/Set/isEmpty)

A Boolean value that indicates whether the set is empty.

[`var count: Int`](/documentation/Swift/Set/count)

The number of elements in the set.

[`var capacity: Int`](/documentation/Swift/Set/capacity)

The total number of elements that the set can contain without
allocating new storage.

### Testing for Membership

[`func contains(Element) -> Bool`](/documentation/Swift/Set/contains(_:))

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

### Adding Elements

[`func insert(Element) -> (inserted: Bool, memberAfterInsert: Element)`](/documentation/Swift/Set/insert(_:)-nads)

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

[`func insert<ConcreteElement>(ConcreteElement) -> (inserted: Bool, memberAfterInsert: ConcreteElement)`](/documentation/Swift/Set/insert(_:)-yar4)

[`func update(with: Element) -> Element?`](/documentation/Swift/Set/update(with:)-2n6tk)

Inserts the given element into the set unconditionally.

[`func update<ConcreteElement>(with: ConcreteElement) -> ConcreteElement?`](/documentation/Swift/Set/update(with:)-7r2g)

[`func reserveCapacity(Int)`](/documentation/Swift/Set/reserveCapacity(_:))

Reserves enough space to store the specified number of elements.

### Removing Elements

[`func filter<E>((Element) throws(E) -> Bool) throws(E) -> Set<Element>`](/documentation/Swift/Set/filter(_:))

Returns a new set containing the elements of the set that satisfy the
given predicate.

[`func remove(Element) -> Element?`](/documentation/Swift/Set/remove(_:)-8p2tv)

Removes the specified element from the set.

[`func remove<ConcreteElement>(ConcreteElement) -> ConcreteElement?`](/documentation/Swift/Set/remove(_:)-4d3i1)

[`func removeFirst() -> Element`](/documentation/Swift/Set/removeFirst())

Removes the first element of the set.

[`func remove(at: Set<Element>.Index) -> Element`](/documentation/Swift/Set/remove(at:))

Removes the element at the given index of the set.

[`func removeAll(keepingCapacity: Bool)`](/documentation/Swift/Set/removeAll(keepingCapacity:))

Removes all members from the set.

### Combining Sets

[`func union<S>(S) -> Set<Element>`](/documentation/Swift/Set/union(_:))

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

[`func formUnion<S>(S)`](/documentation/Swift/Set/formUnion(_:))

Inserts the elements of the given sequence into the set.

[`func intersection(Set<Element>) -> Set<Element>`](/documentation/Swift/Set/intersection(_:)-1zh8f)

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

[`func intersection<S>(S) -> Set<Element>`](/documentation/Swift/Set/intersection(_:)-6uts9)

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

[`func formIntersection<S>(S)`](/documentation/Swift/Set/formIntersection(_:))

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

[`func symmetricDifference<S>(S) -> Set<Element>`](/documentation/Swift/Set/symmetricDifference(_:))

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

[`func formSymmetricDifference(Set<Element>)`](/documentation/Swift/Set/formSymmetricDifference(_:)-22p0m)

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)`](/documentation/Swift/Set/formSymmetricDifference(_:)-5u38b)

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

[`func subtract(Set<Element>)`](/documentation/Swift/Set/subtract(_:)-8gc48)

Removes the elements of the given set from this set.

[`func subtract<S>(S)`](/documentation/Swift/Set/subtract(_:)-7cd3y)

Removes the elements of the given sequence from the set.

[`func subtracting(Set<Element>) -> Set<Element>`](/documentation/Swift/Set/subtracting(_:)-3n4lc)

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

[`func subtracting<S>(S) -> Set<Element>`](/documentation/Swift/Set/subtracting(_:)-2qge3)

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

### Comparing Sets

[`static func == (Set<Element>, Set<Element>) -> Bool`](/documentation/Swift/Set/==(_:_:))

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

[`static func != (borrowing Self, borrowing Self) -> Bool`](/documentation/Swift/Set/!=(_:_:))

Returns a Boolean value indicating whether two values are not equal.

[`func isSubset(of: Set<Element>) -> Bool`](/documentation/Swift/Set/isSubset(of:)-1d7pp)

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

[`func isSubset<S>(of: S) -> Bool`](/documentation/Swift/Set/isSubset(of:)-6qyo5)

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

[`func isStrictSubset(of: Set<Element>) -> Bool`](/documentation/Swift/Set/isStrictSubset(of:)-96vc3)

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

[`func isStrictSubset<S>(of: S) -> Bool`](/documentation/Swift/Set/isStrictSubset(of:)-787sx)

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

[`func isSuperset(of: Set<Element>) -> Bool`](/documentation/Swift/Set/isSuperset(of:)-9iz62)

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

[`func isSuperset<S>(of: S) -> Bool`](/documentation/Swift/Set/isSuperset(of:)-90hri)

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

[`func isStrictSuperset(of: Set<Element>) -> Bool`](/documentation/Swift/Set/isStrictSuperset(of:)-4d27m)

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

[`func isStrictSuperset<S>(of: S) -> Bool`](/documentation/Swift/Set/isStrictSuperset(of:)-58ejg)

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

[`func isDisjoint(with: Set<Element>) -> Bool`](/documentation/Swift/Set/isDisjoint(with:)-8ngmk)

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

[`func isDisjoint<S>(with: S) -> Bool`](/documentation/Swift/Set/isDisjoint(with:)-2onid)

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

### Accessing Individual Elements

[`var first: Self.Element?`](/documentation/Swift/Set/first)

The first element of the collection.

[`func randomElement() -> Self.Element?`](/documentation/Swift/Set/randomElement())

Returns a random element of the collection.

[`func randomElement<T>(using: inout T) -> Self.Element?`](/documentation/Swift/Set/randomElement(using:))

Returns a random element of the collection, using the given generator as
a source for randomness.

### Finding Elements

[`subscript(Set<Element>.Index) -> Element`](/documentation/Swift/Set/subscript(_:))

Accesses the member at the given position.

[`func contains(where: (Self.Element) throws -> Bool) rethrows -> Bool`](/documentation/Swift/Set/contains(where:))

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

[`func allSatisfy((Self.Element) throws -> Bool) rethrows -> Bool`](/documentation/Swift/Set/allSatisfy(_:))

Returns a Boolean value indicating whether every element of a sequence
satisfies a given predicate.

[`func first(where: (Self.Element) throws -> Bool) rethrows -> Self.Element?`](/documentation/Swift/Set/first(where:))

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

[`func firstIndex(of: Element) -> Set<Element>.Index?`](/documentation/Swift/Set/firstIndex(of:))

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

[`func firstIndex(where: (Self.Element) throws -> Bool) rethrows -> Self.Index?`](/documentation/Swift/Set/firstIndex(where:))

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

[`func index(of: Self.Element) -> Self.Index?`](/documentation/Swift/Set/index(of:))

Returns the first index where the specified value appears in the
collection.

[`func min() -> Self.Element?`](/documentation/Swift/Set/min())

Returns the minimum element in the sequence.

[`func min(by: (Self.Element, Self.Element) throws -> Bool) rethrows -> Self.Element?`](/documentation/Swift/Set/min(by:))

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

[`func max() -> Self.Element?`](/documentation/Swift/Set/max())

Returns the maximum element in the sequence.

[`func max(by: (Self.Element, Self.Element) throws -> Bool) rethrows -> Self.Element?`](/documentation/Swift/Set/max(by:))

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

### Transforming a Set

[`func compactMap<ElementOfResult>((Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]`](/documentation/Swift/Set/compactMap(_:))

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

[`func flatMap<SegmentOfResult>((Self.Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element]`](/documentation/Swift/Set/flatMap(_:)-i3my)

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

[`func flatMap<ElementOfResult>((Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]`](/documentation/Swift/Set/flatMap(_:)-6chuh)

[`func reduce<Result>(Result, (Result, Self.Element) throws -> Result) rethrows -> Result`](/documentation/Swift/Set/reduce(_:_:))

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

[`func reduce<Result>(into: Result, (inout Result, Self.Element) throws -> ()) rethrows -> Result`](/documentation/Swift/Set/reduce(into:_:))

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

[`func sorted() -> [Self.Element]`](/documentation/Swift/Set/sorted())

Returns the elements of the sequence, sorted.

[`func sorted(by: (Self.Element, Self.Element) throws -> Bool) rethrows -> [Self.Element]`](/documentation/Swift/Set/sorted(by:))

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

[`func shuffled() -> [Self.Element]`](/documentation/Swift/Set/shuffled())

Returns the elements of the sequence, shuffled.

[`func shuffled<T>(using: inout T) -> [Self.Element]`](/documentation/Swift/Set/shuffled(using:))

Returns the elements of the sequence, shuffled using the given generator
as a source for randomness.

[`var lazy: LazySequence<Self>`](/documentation/Swift/Set/lazy)

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

### Iterating over a Set

[`func enumerated() -> EnumeratedSequence<Self>`](/documentation/Swift/Set/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 forEach((Self.Element) throws -> Void) rethrows`](/documentation/Swift/Set/forEach(_:))

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

[`func makeIterator() -> Set<Element>.Iterator`](/documentation/Swift/Set/makeIterator())

Returns an iterator over the members of the set.

[`var underestimatedCount: Int`](/documentation/Swift/Set/underestimatedCount)

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

### Performing Collection Operations

  <doc://com.apple.Swift/documentation/Swift/order-dependent-operations-on-set>

### Encoding and Decoding

[`func encode(to: any Encoder) throws`](/documentation/Swift/Set/encode(to:))

Encodes the elements of this set into the given encoder in an unkeyed
container.

[`init(from: any Decoder) throws`](/documentation/Swift/Set/init(from:))

Creates a new set by decoding from the given decoder.

### Describing a Set

[`func hash(into: inout Hasher)`](/documentation/Swift/Set/hash(into:))

Hashes the essential components of this value by feeding them into the
given hasher.

[`var description: String`](/documentation/Swift/Set/description)

A string that represents the contents of the set.

[`var debugDescription: String`](/documentation/Swift/Set/debugDescription)

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

[`var customMirror: Mirror`](/documentation/Swift/Set/customMirror)

A mirror that reflects the set.

### Reference Types

Use bridged reference types when you need reference semantics or Foundation-specific
behavior.

  <doc://com.apple.documentation/documentation/Foundation/NSSet>

  <doc://com.apple.documentation/documentation/Foundation/NSMutableSet>

### Supporting Types

[`struct Index`](/documentation/Swift/Set/Index)

The position of an element in a set.

[`struct Iterator`](/documentation/Swift/Set/Iterator)

An iterator over the members of a `Set<Element>`.

### Infrequently Used Functionality

[`init(arrayLiteral: Element...)`](/documentation/Swift/Set/init(arrayLiteral:))

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

[`func withContiguousStorageIfAvailable<R>((UnsafeBufferPointer<Self.Element>) throws -> R) rethrows -> R?`](/documentation/Swift/Set/withContiguousStorageIfAvailable(_:))

Executes a closure on the sequence’s contiguous storage.

### Instance Methods

[`func isTriviallyIdentical(to: Set<Element>) -> Bool`](/documentation/Swift/Set/isTriviallyIdentical(to:))

Returns a boolean value indicating whether this set is identical to
`other`.

### Type Aliases

[`typealias Specification`](/documentation/Swift/Set/Specification)

[`typealias UnderlyingSequence`](/documentation/Swift/Set/UnderlyingSequence)

[`typealias UnwrappedType`](/documentation/Swift/Set/UnwrappedType)

[`typealias ValueType`](/documentation/Swift/Set/ValueType)

### Type Properties

[`static var defaultResolverSpecification: some ResolverSpecification`](/documentation/Swift/Set/defaultResolverSpecification)

### Default Implementations

[Collection Implementations](/documentation/Swift/Set/Collection-Implementations)

[CustomDebugStringConvertible Implementations](/documentation/Swift/Set/CustomDebugStringConvertible-Implementations)

[CustomReflectable Implementations](/documentation/Swift/Set/CustomReflectable-Implementations)

[CustomStringConvertible Implementations](/documentation/Swift/Set/CustomStringConvertible-Implementations)

[Decodable Implementations](/documentation/Swift/Set/Decodable-Implementations)

[Encodable Implementations](/documentation/Swift/Set/Encodable-Implementations)

[Equatable Implementations](/documentation/Swift/Set/Equatable-Implementations)

[ExpressibleByArrayLiteral Implementations](/documentation/Swift/Set/ExpressibleByArrayLiteral-Implementations)

[Hashable Implementations](/documentation/Swift/Set/Hashable-Implementations)

[IntentValueConvertible Implementations](/documentation/Swift/Set/IntentValueConvertible-Implementations)

[IntentValueExpressing Implementations](/documentation/Swift/Set/IntentValueExpressing-Implementations)

[Sequence Implementations](/documentation/Swift/Set/Sequence-Implementations)

[SetAlgebra Implementations](/documentation/Swift/Set/SetAlgebra-Implementations)

## Relationships

### Conforms To

[`SendableMetatype`](/documentation/Swift/SendableMetatype)

[`IntentValueConvertible`](/documentation/AppIntents/IntentValueConvertible)

[`Sendable`](/documentation/Swift/Sendable)

[`Decodable`](/documentation/Swift/Decodable)

[`Copyable`](/documentation/Swift/Copyable)

[`Encodable`](/documentation/Swift/Encodable)

[`IntentValueExpressing`](/documentation/AppIntents/IntentValueExpressing)

[`SetAlgebra`](/documentation/Swift/SetAlgebra)

[`CVarArg`](/documentation/Swift/CVarArg)

[`Hashable`](/documentation/Swift/Hashable)

[`Escapable`](/documentation/Swift/Escapable)

[`CustomStringConvertible`](/documentation/Swift/CustomStringConvertible)

[`ExpressibleByArrayLiteral`](/documentation/Swift/ExpressibleByArrayLiteral)

[`CustomReflectable`](/documentation/Swift/CustomReflectable)

[`CustomDebugStringConvertible`](/documentation/Swift/CustomDebugStringConvertible)

[`Equatable`](/documentation/Swift/Equatable)

[`CVAttachmentValueRepresentable`](/documentation/CoreVideo/CVAttachmentValueRepresentable)

[`Sequence`](/documentation/Swift/Sequence)

[`Collection`](/documentation/Swift/Collection)

[`AppEntityCollectionValue`](/documentation/AppIntents/AppEntityCollectionValue)

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)