Set

struct Set

An unordered collection of unique elements.

Inheritance Collection, CustomDebugStringConvertible, CustomReflectable, CustomStringConvertible, Equatable, ExpressibleByArrayLiteral, Hashable, Sequence, SetAlgebra
Nested Types Set.Index, Set.Iterator

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:

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

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.

Initializers

init init() Required

Creates an empty set.

This is equivalent to initializing with an empty array literal. For example:

var emptySet = Set<Int>()
print(emptySet.isEmpty)
// Prints "true"

emptySet = []
print(emptySet.isEmpty)
// Prints "true"

Declaration

@inlinable public init()
init init(_:) Required

Creates a new set from a finite sequence of items.

Use this initializer to create a new set from an existing sequence, for example, an array or a range.

let validIndices = Set(0..<7).subtracting([2, 4, 5])
print(validIndices)
// Prints "[6, 0, 1, 3]"

This initializer can also be used to restore set methods after performing sequence operations such as filter(_:) or map(_:) on a set. For example, after filtering a set of prime numbers to remove any below 10, you can create a new set by using this initializer.

let primes: Set = [2, 3, 5, 7, 11, 13, 17, 19, 23]
let laterPrimes = Set(primes.lazy.filter { $0 > 10 })
print(laterPrimes)
// Prints "[17, 19, 23, 11, 13]"
  • Parameter sequence: The elements to use as members of the new set.

Declaration

@inlinable public init<Source>(_ sequence: Source) where Element == Source.Element, Source: Sequence
init init(_:) Required

Creates a new set from a finite sequence of items.

Use this initializer to create a new set from an existing sequence, like an array or a range:

let validIndices = Set(0..<7).subtracting([2, 4, 5])
print(validIndices)
// Prints "[6, 0, 1, 3]"
  • Parameter sequence: The elements to use as members of the new set.

Declaration

@inlinable public init<S>(_ sequence: S) where S: Sequence, Self.Element == S.Element
init init(arrayLiteral:) Required

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

Do not call this initializer directly. It is used by the compiler when you use an array literal. Instead, create a new set using an array literal as its value by enclosing a comma-separated list of values in square brackets. You can use an array literal anywhere a set is expected by the type context.

Here, a set of strings is created from an array literal holding only strings.

let ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]
if ingredients.isSuperset(of: ["sugar", "salt"]) {
    print("Whatever it is, it's bound to be delicious!")
}
// Prints "Whatever it is, it's bound to be delicious!"
  • Parameter elements: A variadic list of elements of the new set.

Declaration

@inlinable public init(arrayLiteral elements: Element)
init init(minimumCapacity:) Required

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

Use this initializer to avoid intermediate reallocations of a set's storage buffer when you know how many elements you'll insert into the set after creation.

  • Parameter minimumCapacity: The minimum number of elements that the newly created set should be able to store without reallocating its storage buffer.

Declaration

public init(minimumCapacity: Int)

Instance Variables

var capacity Required

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

Declaration

var capacity: Int
var count Required

The number of elements in the set.

Complexity: O(1).

Declaration

var count: Int
var count Required

The number of elements in the collection.

To check whether a collection is empty, use its isEmpty property instead of comparing count to zero. Unless the collection guarantees random-access performance, calculating count can be an O(n) operation.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.

Declaration

var count: Int
var customMirror Required

A mirror that reflects the set.

Declaration

var customMirror: Mirror
var debugDescription Required

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

Declaration

var debugDescription: String
var description Required

A string that represents the contents of the set.

Declaration

var description: String
var endIndex Required

The "past the end" position for the set---that is, the position one greater than the last valid subscript argument.

If the set is empty, endIndex is equal to startIndex.

Declaration

var endIndex: Set<Element>.Index
var first Required

The first element of the collection.

If the collection is empty, the value of this property is nil.

let numbers = [10, 20, 30, 40, 50]
if let firstNumber = numbers.first {
    print(firstNumber)
}
// Prints "10"

Declaration

var first: Self.Element?
var isEmpty Required

A Boolean value that indicates whether the set is empty.

Declaration

var isEmpty: Bool
var isEmpty Required

A Boolean value indicating whether the collection is empty.

When you need to check whether your collection is empty, use the isEmpty property instead of checking that the count property is equal to zero. For collections that don't conform to RandomAccessCollection, accessing the count property iterates through the elements of the collection.

let horseName = "Silver"
if horseName.isEmpty {
    print("I've been through the desert on a horse with no name.")
} else {
    print("Hi ho, \(horseName)!")
}
// Prints "Hi ho, Silver!")

Complexity: O(1)

Declaration

var isEmpty: Bool
var isEmpty Required

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

Declaration

var isEmpty: Bool
var lazy Required

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

Declaration

var lazy: LazySequence<Self>
var startIndex Required

The starting position for iterating members of the set.

If the set is empty, startIndex is equal to endIndex.

Declaration

var startIndex: Set<Element>.Index
var underestimatedCount Required

A value less than or equal to the number of elements in the sequence, calculated nondestructively.

The default implementation returns 0. If you provide your own implementation, make sure to compute the value nondestructively.

Complexity: O(1), except if the sequence also conforms to Collection. In this case, see the documentation of Collection.underestimatedCount.

Declaration

var underestimatedCount: Int
var underestimatedCount Required

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

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.

Declaration

var underestimatedCount: Int

Subscripts

subscript subscript(position:) Required

Accesses the member at the given position.

Declaration

@inlinable public subscript(position: Set<Element>.Index) -> Element
subscript subscript(r:) Required

Accesses the contiguous subrange of the collection's elements specified by a range expression.

The range expression is converted to a concrete subrange relative to this collection. For example, using a PartialRangeFrom range expression with an array accesses the subrange from the start of the range expression until the end of the array.

let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
let streetsSlice = streets[2...]
print(streetsSlice)
// ["Channing", "Douglas", "Evarts"]

The accessed slice uses the same indices for the same elements as the original collection uses. This example searches streetsSlice for one of the strings in the slice, and then uses that index in the original array.

let index = streetsSlice.firstIndex(of: "Evarts")    // 4
print(streets[index!])
// "Evarts"

Always use the slice's startIndex property instead of assuming that its indices start at a particular value. Attempting to access an element by using an index outside the bounds of the slice's indices may result in a runtime error, even if that index is valid for the original collection.

print(streetsSlice.startIndex)
// 2
print(streetsSlice[2])
// "Channing"

print(streetsSlice[0])
// error: Index out of bounds
  • Parameter bounds: A range of the collection's indices. The bounds of the range must be valid indices of the collection.

Complexity: O(1)

Declaration

@inlinable public subscript<R>(r: R) where R: RangeExpression, Self.Index == R.Bound -> Self.SubSequence
subscript subscript(x:) Required

Declaration

@inlinable public subscript(x: (UnboundedRange_) -> ()) -> Self.SubSequence

Instance Methods

func allSatisfy(_ predicate: (Self.Element) throws -> Bool) rethrows -> Bool Required

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

The following code uses this method to test whether all the names in an array have at least five characters:

let names = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
let allHaveAtLeastFive = names.allSatisfy({ $0.count >= 5 })
// allHaveAtLeastFive == true
  • Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value that indicates whether the passed element satisfies a condition.

Complexity: O(n), where n is the length of the sequence.

Declaration

@inlinable public func allSatisfy(_ predicate: (Self.Element) throws -> Bool) rethrows -> Bool
func compactMap(_ transform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] Required

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

Use this method to receive an array of non-optional values when your transformation produces an optional value.

In this example, note the difference in the result of using map and compactMap with a transformation that returns an optional Int value.

let possibleNumbers = ["1", "2", "three", "///4///", "5"]

let mapped: [Int?] = possibleNumbers.map { str in Int(str) }
// [1, 2, nil, nil, 5]

let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) }
// [1, 2, 5]
  • Parameter transform: A closure that accepts an element of this sequence as its argument and returns an optional value.

Complexity: O(m + n), where n is the length of this sequence and m is the length of the result.

Declaration

@inlinable public func compactMap<ElementOfResult>(_ transform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]
func contains(_ member: Element) -> Bool Required

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

This example uses the contains(_:) method to test whether an integer is a member of a set of prime numbers.

let primes: Set = [2, 3, 5, 7]
let x = 5
if primes.contains(x) {
    print("\(x) is prime!")
} else {
    print("\(x). Not prime.")
}
// Prints "5 is prime!"
  • Parameter member: An element to look for in the set.

Complexity: O(1)

Declaration

@inlinable public func contains(_ member: Element) -> Bool
func contains(where predicate: (Self.Element) throws -> Bool) rethrows -> Bool Required

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

You can use the predicate to check for an element of a type that doesn't conform to the Equatable protocol, such as the HTTPResponse enumeration in this example.

enum HTTPResponse {
    case ok
    case error(Int)
}

let lastThreeResponses: [HTTPResponse] = [.ok, .ok, .error(404)]
let hadError = lastThreeResponses.contains { element in
    if case .error = element {
        return true
    } else {
        return false
    }
}
// 'hadError' == true

Alternatively, a predicate can be satisfied by a range of Equatable elements or a general condition. This example shows how you can check an array for an expense greater than $100.

let expenses = [21.37, 55.21, 9.32, 10.18, 388.77, 11.41]
let hasBigPurchase = expenses.contains { $0 > 100 }
// 'hasBigPurchase' == true
  • Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value that indicates whether the passed element represents a match.

Complexity: O(n), where n is the length of the sequence.

Declaration

@inlinable public func contains(where predicate: (Self.Element) throws -> Bool) rethrows -> Bool
func distance(from start: Self.Index, to end: Self.Index) -> Int Required

Returns the distance between two indices.

Unless the collection conforms to the BidirectionalCollection protocol, start must be less than or equal to end.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the resulting distance.

Declaration

@inlinable public func distance(from start: Self.Index, to end: Self.Index) -> Int
func drop(while predicate: (Self.Element) throws -> Bool) rethrows -> DropWhileSequence<Self> Required

Returns a sequence by skipping the initial, consecutive elements that satisfy the given predicate.

The following example uses the drop(while:) method to skip over the positive numbers at the beginning of the numbers array. The result begins with the first element of numbers that does not satisfy predicate.

let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
let startingWithNegative = numbers.drop(while: { $0 > 0 })
// startingWithNegative == [-2, 9, -6, 10, 1]

If predicate matches every element in the sequence, the result is an empty sequence.

  • Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the result.

Complexity: O(k), where k is the number of elements to drop from the beginning of the sequence.

Declaration

@inlinable public func drop(while predicate: (Self.Element) throws -> Bool) rethrows -> DropWhileSequence<Self>
func drop(while predicate: (Self.Element) throws -> Bool) rethrows -> Self.SubSequence Required

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

  • Parameter predicate: A closure that takes an element of the sequence as its argument and returns true if the element should be skipped or false if it should be included. Once the predicate returns false it will not be called again.

Complexity: O(n), where n is the length of the collection.

Declaration

@inlinable public func drop(while predicate: (Self.Element) throws -> Bool) rethrows -> Self.SubSequence
func dropFirst(_ k: Int = 1) -> DropFirstSequence<Self> Required

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

If the number of elements to drop exceeds the number of elements in the sequence, the result is an empty sequence.

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropFirst(2))
// Prints "[3, 4, 5]"
print(numbers.dropFirst(10))
// Prints "[]"
  • Parameter k: The number of elements to drop from the beginning of the sequence. k must be greater than or equal to zero.

Complexity: O(1), with O(k) deferred to each iteration of the result, where k is the number of elements to drop from the beginning of the sequence.

Declaration

@inlinable public func dropFirst(_ k: Int = 1) -> DropFirstSequence<Self>
func dropFirst(_ k: Int = 1) -> Self.SubSequence Required

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

If the number of elements to drop exceeds the number of elements in the collection, the result is an empty subsequence.

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropFirst(2))
// Prints "[3, 4, 5]"
print(numbers.dropFirst(10))
// Prints "[]"
  • Parameter k: The number of elements to drop from the beginning of the collection. k must be greater than or equal to zero.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the number of elements to drop from the beginning of the collection.

Declaration

@inlinable public func dropFirst(_ k: Int = 1) -> Self.SubSequence
func dropLast(_ k: Int = 1) -> [Self.Element] Required

Returns a sequence containing all but the given number of final elements.

The sequence must be finite. If the number of elements to drop exceeds the number of elements in the sequence, the result is an empty sequence.

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropLast(2))
// Prints "[1, 2, 3]"
print(numbers.dropLast(10))
// Prints "[]"
  • Parameter n: The number of elements to drop off the end of the sequence. n must be greater than or equal to zero.

Complexity: O(n), where n is the length of the sequence.

Declaration

@inlinable public func dropLast(_ k: Int = 1) -> [Self.Element]
func dropLast(_ k: Int = 1) -> Self.SubSequence Required

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

If the number of elements to drop exceeds the number of elements in the collection, the result is an empty subsequence.

let numbers = [1, 2, 3, 4, 5]
print(numbers.dropLast(2))
// Prints "[1, 2, 3]"
print(numbers.dropLast(10))
// Prints "[]"
  • Parameter k: The number of elements to drop off the end of the collection. k must be greater than or equal to zero.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.

Declaration

@inlinable public func dropLast(_ k: Int = 1) -> Self.SubSequence
func elementsEqual(_ other: OtherSequence, by areEquivalent: (Self.Element, OtherSequence.Element) throws -> Bool) rethrows -> Bool Required

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

At least one of the sequences must be finite.

The predicate must be a equivalence relation over the elements. That is, for any elements a, b, and c, the following conditions must hold:

Complexity: O(m), where m is the lesser of the length of the sequence and the length of other.

Declaration

@inlinable public func elementsEqual<OtherSequence>(_ other: OtherSequence, by areEquivalent: (Self.Element, OtherSequence.Element) throws -> Bool) rethrows -> Bool where OtherSequence: Sequence
func enumerated() -> EnumeratedSequence<Self> Required

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

This example enumerates the characters of the string "Swift" and prints each character along with its place in the string.

for (n, c) in "Swift".enumerated() {
    print("\(n): '\(c)'")
}
// Prints "0: 'S'"
// Prints "1: 'w'"
// Prints "2: 'i'"
// Prints "3: 'f'"
// Prints "4: 't'"

When you enumerate a collection, the integer part of each pair is a counter for the enumeration, but is not necessarily the index of the paired value. These counters can be used as indices only in instances of zero-based, integer-indexed collections, such as Array and ContiguousArray. For other collections the counters may be out of range or of the wrong type to use as an index. To iterate over the elements of a collection with its indices, use the zip(_:_:) function.

This example iterates over the indices and elements of a set, building a list consisting of indices of names with five or fewer letters.

let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
var shorterIndices: [Set<String>.Index] = []
for (i, name) in zip(names.indices, names) {
    if name.count <= 5 {
        shorterIndices.append(i)
    }
}

Now that the shorterIndices array holds the indices of the shorter names in the names set, you can use those indices to access elements in the set.

for i in shorterIndices {
    print(names[i])
}
// Prints "Sofia"
// Prints "Mateo"

Complexity: O(1)

Declaration

@inlinable public func enumerated() -> EnumeratedSequence<Self>
func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> [Self.Element] Required

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

In this example, filter(_:) is used to include only names shorter than five characters.

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let shortNames = cast.filter { $0.count < 5 }
print(shortNames)
// Prints "["Kim", "Karl"]"
  • Parameter isIncluded: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the returned array.

Complexity: O(n), where n is the length of the sequence.

Declaration

@inlinable public func filter(_ isIncluded: (Self.Element) throws -> Bool) rethrows -> [Self.Element]
func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> Set<Element> Required

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

In this example, filter(_:) is used to include only names shorter than five characters.

let cast: Set = ["Vivien", "Marlon", "Kim", "Karl"]
let shortNames = cast.filter { $0.count < 5 }

shortNames.isSubset(of: cast)
// true
shortNames.contains("Vivien")
// false
  • Parameter isIncluded: A closure that takes an element as its argument and returns a Boolean value indicating whether the element should be included in the returned set.

Declaration

@available(swift 4.0) @inlinable public func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> Set<Element>
func first(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Element? Required

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

The following example uses the first(where:) method to find the first negative number in an array of integers:

let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
if let firstNegative = numbers.first(where: { $0 < 0 }) {
    print("The first negative number is \(firstNegative).")
}
// Prints "The first negative number is -2."
  • Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match.

Complexity: O(n), where n is the length of the sequence.

Declaration

@inlinable public func first(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Element?
func firstIndex(of member: Element) -> Set<Element>.Index? Required

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

  • Parameter member: An element to search for in the set.

Complexity: O(1)

Declaration

@inlinable public func firstIndex(of member: Element) -> Set<Element>.Index?
func firstIndex(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Index? Required

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

You can use the predicate to find an element of a type that doesn't conform to the Equatable protocol or to find an element that matches particular criteria. Here's an example that finds a student name that begins with the letter "A":

let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
if let i = students.firstIndex(where: { $0.hasPrefix("A") }) {
    print("\(students[i]) starts with 'A'!")
}
// Prints "Abena starts with 'A'!"
  • Parameter predicate: A closure that takes an element as its argument and returns a Boolean value that indicates whether the passed element represents a match.

Complexity: O(n), where n is the length of the collection.

Declaration

@inlinable public func firstIndex(where predicate: (Self.Element) throws -> Bool) rethrows -> Self.Index?
func flatMap(_ transform: (Self.Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] Required

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

Use this method to receive a single-level collection when your transformation produces a sequence or collection for each element.

In this example, note the difference in the result of using map and flatMap with a transformation that returns an array.

let numbers = [1, 2, 3, 4]

let mapped = numbers.map { Array(repeating: $0, count: $0) }
// [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]

let flatMapped = numbers.flatMap { Array(repeating: $0, count: $0) }
// [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

In fact, s.flatMap(transform) is equivalent to Array(s.map(transform).joined()).

  • Parameter transform: A closure that accepts an element of this sequence as its argument and returns a sequence or collection.

Complexity: O(m + n), where n is the length of this sequence and m is the length of the result.

Declaration

@inlinable public func flatMap<SegmentOfResult>(_ transform: (Self.Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Element] where SegmentOfResult: Sequence
func flatMap(_ transform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] Required

Declaration

@available(swift, deprecated: 4.1, renamed: "compactMap(_:)", message: "Please use compactMap(_:) for the case where closure returns an optional value") public func flatMap<ElementOfResult>(_ transform: (Self.Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult]
func forEach(_ body: (Self.Element) throws -> Void) rethrows Required

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

The two loops in the following example produce the same output:

let numberWords = ["one", "two", "three"]
for word in numberWords {
    print(word)
}
// Prints "one"
// Prints "two"
// Prints "three"

numberWords.forEach { word in
    print(word)
}
// Same as above

Using the forEach method is distinct from a for-in loop in two important ways:

  1. You cannot use a break or continue statement to exit the current call of the body closure or skip subsequent calls.
  2. Using the return statement in the body closure will exit only from the current call to body, not from any outer scope, and won't skip subsequent calls.
  • Parameter body: A closure that takes an element of the sequence as a parameter.

Declaration

@inlinable public func forEach(_ body: (Self.Element) throws -> Void) rethrows
func formIndex(_ i: inout Self.Index, offsetBy distance: Int) Required

Offsets the given index by the specified distance.

The value passed as distance must not offset i beyond the bounds of the collection.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the absolute value of distance.

Declaration

@inlinable public func formIndex(_ i: inout Self.Index, offsetBy distance: Int)
func formIndex(_ i: inout Self.Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Bool Required

Offsets the given index by the specified distance, or so that it equals the given limiting index.

The value passed as distance must not offset i beyond the bounds of the collection, unless the index passed as limit prevents offsetting beyond those bounds.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the absolute value of distance.

Declaration

@inlinable public func formIndex(_ i: inout Self.Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Bool
func formIndex(after i: inout Set<Element>.Index) Required

Replaces the given index with its successor.

  • Parameter i: A valid index of the collection. i must be less than endIndex.

Declaration

@inlinable public func formIndex(after i: inout Set<Element>.Index)
func formIndex(after i: inout Self.Index) Required

Replaces the given index with its successor.

  • Parameter i: A valid index of the collection. i must be less than endIndex.

Declaration

@inlinable public func formIndex(after i: inout Self.Index)
func formIntersection(_ other: S) Required

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

In the following example, the elements of the employees set that are not also members of the neighbors set are removed. In particular, the names "Alicia", "Chris", and "Diana" are removed.

var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let neighbors = ["Bethany", "Eric", "Forlani", "Greta"]
employees.formIntersection(neighbors)
print(employees)
// Prints "["Bethany", "Eric"]"
  • Parameter other: A sequence of elements. other must be finite.

Declaration

@inlinable public mutating func formIntersection<S>(_ other: S) where Element == S.Element, S: Sequence
func formSymmetricDifference(_ other: S) Required

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

In the following example, the elements of the employees set that are also members of neighbors are removed from employees, while the elements of neighbors that are not members of employees are added to employees. In particular, the names "Bethany" and "Eric" are removed from employees while the name "Forlani" is added.

var employees: Set = ["Alicia", "Bethany", "Diana", "Eric"]
let neighbors = ["Bethany", "Eric", "Forlani"]
employees.formSymmetricDifference(neighbors)
print(employees)
// Prints "["Diana", "Forlani", "Alicia"]"
  • Parameter other: A sequence of elements. other must be finite.

Declaration

@inlinable public mutating func formSymmetricDifference<S>(_ other: S) where Element == S.Element, S: Sequence
func formSymmetricDifference(_ other: Set<Element>) Required

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.

In the following example, the elements of the employees set that are also members of neighbors are removed from employees, while the elements of neighbors that are not members of employees are added to employees. In particular, the names "Alicia", "Chris", and "Diana" are removed from employees while the names "Forlani" and "Greta" are added.

var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
employees.formSymmetricDifference(neighbors)
print(employees)
// Prints "["Diana", "Chris", "Forlani", "Alicia", "Greta"]"
  • Parameter other: Another set.

Declaration

@inlinable public mutating func formSymmetricDifference(_ other: Set<Element>)
func formUnion(_ other: S) Required

Inserts the elements of the given sequence into the set.

If the set already contains one or more elements that are also in other, the existing members are kept. If other contains multiple instances of equivalent elements, only the first instance is kept.

var attendees: Set = ["Alicia", "Bethany", "Diana"]
let visitors = ["Diana", "Marcia", "Nathaniel"]
attendees.formUnion(visitors)
print(attendees)
// Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"
  • Parameter other: A sequence of elements. other must be finite.

Declaration

@inlinable public mutating func formUnion<S>(_ other: S) where Element == S.Element, S: Sequence
func hash(into hasher: inout Hasher) Required

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

  • Parameter hasher: The hasher to use when combining the components of this instance.

Declaration

@inlinable public func hash(into hasher: inout Hasher)
func index(_ i: Self.Index, offsetBy distance: Int) -> Self.Index Required

Returns an index that is the specified distance from the given index.

The following example obtains an index advanced four positions from a string's starting index and then prints the character at that position.

let s = "Swift"
let i = s.index(s.startIndex, offsetBy: 4)
print(s[i])
// Prints "t"

The value passed as distance must not offset i beyond the bounds of the collection.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the absolute value of distance.

Declaration

@inlinable public func index(_ i: Self.Index, offsetBy distance: Int) -> Self.Index
func index(_ i: Self.Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Self.Index? Required

Returns an index that is the specified distance from the given index, unless that distance is beyond a given limiting index.

The following example obtains an index advanced four positions from a string's starting index and then prints the character at that position. The operation doesn't require going beyond the limiting s.endIndex value, so it succeeds.

let s = "Swift"
if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) {
    print(s[i])
}
// Prints "t"

The next example attempts to retrieve an index six positions from s.startIndex but fails, because that distance is beyond the index passed as limit.

let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex)
print(j)
// Prints "nil"

The value passed as distance must not offset i beyond the bounds of the collection, unless the index passed as limit prevents offsetting beyond those bounds.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the absolute value of distance.

Declaration

@inlinable public func index(_ i: Self.Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Self.Index?
func index(after i: Set<Element>.Index) -> Set<Element>.Index Required

Returns the position immediately after the given index.

The successor of an index must be well defined. For an index i into a collection c, calling c.index(after: i) returns the same index every time.

  • Parameter i: A valid index of the collection. i must be less than endIndex.

Declaration

@inlinable public func index(after i: Set<Element>.Index) -> Set<Element>.Index
func insert(_ newMember: Element) -> (inserted: Bool, memberAfterInsert: Element) Required

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

If an element equal to newMember is already contained in the set, this method has no effect. In the following example, a new element is inserted into classDays, a set of days of the week. When an existing element is inserted, the classDays set does not change.

enum DayOfTheWeek: Int {
    case sunday, monday, tuesday, wednesday, thursday,
        friday, saturday
}

var classDays: Set<DayOfTheWeek> = [.wednesday, .friday]
print(classDays.insert(.monday))
// Prints "(true, .monday)"
print(classDays)
// Prints "[.friday, .wednesday, .monday]"

print(classDays.insert(.friday))
// Prints "(false, .friday)"
print(classDays)
// Prints "[.friday, .wednesday, .monday]"
  • Parameter newMember: An element to insert into the set.

Declaration

@inlinable public mutating func insert(_ newMember: Element) -> (inserted: Bool, memberAfterInsert: Element)
func intersection(_ other: S) -> Set<Element> Required

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

In the following example, the bothNeighborsAndEmployees set is made up of the elements that are in both the employees and neighbors sets. Elements that are in only one or the other are left out of the result of the intersection.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let neighbors = ["Bethany", "Eric", "Forlani", "Greta"]
let bothNeighborsAndEmployees = employees.intersection(neighbors)
print(bothNeighborsAndEmployees)
// Prints "["Bethany", "Eric"]"
  • Parameter other: A sequence of elements. other must be finite.

Declaration

@inlinable public func intersection<S>(_ other: S) -> Set<Element> where Element == S.Element, S: Sequence
func intersection(_ other: Set<Element>) -> Set<Element> Required

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

In the following example, the bothNeighborsAndEmployees set is made up of the elements that are in both the employees and neighbors sets. Elements that are in only one or the other are left out of the result of the intersection.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
let bothNeighborsAndEmployees = employees.intersection(neighbors)
print(bothNeighborsAndEmployees)
// Prints "["Bethany", "Eric"]"
  • Parameter other: Another set.

Declaration

@inlinable public func intersection(_ other: Set<Element>) -> Set<Element>
func isDisjoint(with other: S) -> Bool Required

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

In the following example, the employees set is disjoint with the elements of the visitors array because no name appears in both.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let visitors = ["Marcia", "Nathaniel", "Olivia"]
print(employees.isDisjoint(with: visitors))
// Prints "true"
  • Parameter other: A sequence of elements. other must be finite.

Declaration

@inlinable public func isDisjoint<S>(with other: S) -> Bool where Element == S.Element, S: Sequence
func isDisjoint(with other: Set<Element>) -> Bool Required

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

In the following example, the employees set is disjoint with the visitors set because no name appears in both sets.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let visitors: Set = ["Marcia", "Nathaniel", "Olivia"]
print(employees.isDisjoint(with: visitors))
// Prints "true"
  • Parameter other: Another set.

Declaration

@inlinable public func isDisjoint(with other: Set<Element>) -> Bool
func isDisjoint(with other: Self) -> Bool Required

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

In the following example, the employees set is disjoint with the visitors set because no name appears in both sets.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let visitors: Set = ["Marcia", "Nathaniel", "Olivia"]
print(employees.isDisjoint(with: visitors))
// Prints "true"
  • Parameter other: A set of the same type as the current set.

Declaration

@inlinable public func isDisjoint(with other: Self) -> Bool
func isStrictSubset(of possibleStrictSuperset: S) -> Bool Required

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

Set A is a strict subset of another set B if every member of A is also a member of B and B contains at least one element that is not a member of A.

let employees = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let attendees: Set = ["Alicia", "Bethany", "Diana"]
print(attendees.isStrictSubset(of: employees))
// Prints "true"

// A set is never a strict subset of itself:
print(attendees.isStrictSubset(of: attendees))
// Prints "false"
  • Parameter possibleStrictSuperset: A sequence of elements. possibleStrictSuperset must be finite.

Declaration

@inlinable public func isStrictSubset<S>(of possibleStrictSuperset: S) -> Bool where Element == S.Element, S: Sequence
func isStrictSubset(of other: Set<Element>) -> Bool Required

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

Set A is a strict subset of another set B if every member of A is also a member of B and B contains at least one element that is not a member of A.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let attendees: Set = ["Alicia", "Bethany", "Diana"]
print(attendees.isStrictSubset(of: employees))
// Prints "true"

// A set is never a strict subset of itself:
print(attendees.isStrictSubset(of: attendees))
// Prints "false"
  • Parameter other: Another set.

Declaration

@inlinable public func isStrictSubset(of other: Set<Element>) -> Bool
func isStrictSubset(of other: Self) -> Bool Required

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

Set A is a strict subset of another set B if every member of A is also a member of B and B contains at least one element that is not a member of A.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let attendees: Set = ["Alicia", "Bethany", "Diana"]
print(attendees.isStrictSubset(of: employees))
// Prints "true"

// A set is never a strict subset of itself:
print(attendees.isStrictSubset(of: attendees))
// Prints "false"
  • Parameter other: A set of the same type as the current set.

Declaration

@inlinable public func isStrictSubset(of other: Self) -> Bool
func isStrictSuperset(of possibleStrictSubset: S) -> Bool Required

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

Set A is a strict superset of another set B if every member of B is also a member of A and A contains at least one element that is not a member of B.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let attendees = ["Alicia", "Bethany", "Diana"]
print(employees.isStrictSuperset(of: attendees))
// Prints "true"
print(employees.isStrictSuperset(of: employees))
// Prints "false"
  • Parameter possibleStrictSubset: A sequence of elements. possibleStrictSubset must be finite.

Declaration

@inlinable public func isStrictSuperset<S>(of possibleStrictSubset: S) -> Bool where Element == S.Element, S: Sequence
func isStrictSuperset(of other: Set<Element>) -> Bool Required

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

Set A is a strict superset of another set B if every member of B is also a member of A and A contains at least one element that is not a member of B.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let attendees: Set = ["Alicia", "Bethany", "Diana"]
print(employees.isStrictSuperset(of: attendees))
// Prints "true"
print(employees.isStrictSuperset(of: employees))
// Prints "false"
  • Parameter other: Another set.

Declaration

@inlinable public func isStrictSuperset(of other: Set<Element>) -> Bool
func isStrictSuperset(of other: Self) -> Bool Required

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

Set A is a strict superset of another set B if every member of B is also a member of A and A contains at least one element that is not a member of B.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let attendees: Set = ["Alicia", "Bethany", "Diana"]
print(employees.isStrictSuperset(of: attendees))
// Prints "true"

// A set is never a strict superset of itself:
print(employees.isStrictSuperset(of: employees))
// Prints "false"
  • Parameter other: A set of the same type as the current set.

Declaration

@inlinable public func isStrictSuperset(of other: Self) -> Bool
func isSubset(of possibleSuperset: S) -> Bool Required

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

Set A is a subset of another set B if every member of A is also a member of B.

let employees = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let attendees: Set = ["Alicia", "Bethany", "Diana"]
print(attendees.isSubset(of: employees))
// Prints "true"
  • Parameter possibleSuperset: A sequence of elements. possibleSuperset must be finite.

Declaration

@inlinable public func isSubset<S>(of possibleSuperset: S) -> Bool where Element == S.Element, S: Sequence
func isSubset(of other: Set<Element>) -> Bool Required

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

Set A is a subset of another set B if every member of A is also a member of B.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let attendees: Set = ["Alicia", "Bethany", "Diana"]
print(attendees.isSubset(of: employees))
// Prints "true"
  • Parameter other: Another set.

Declaration

@inlinable public func isSubset(of other: Set<Element>) -> Bool
func isSubset(of other: Self) -> Bool Required

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

Set A is a subset of another set B if every member of A is also a member of B.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let attendees: Set = ["Alicia", "Bethany", "Diana"]
print(attendees.isSubset(of: employees))
// Prints "true"
  • Parameter other: A set of the same type as the current set.

Declaration

@inlinable public func isSubset(of other: Self) -> Bool
func isSuperset(of possibleSubset: S) -> Bool Required

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

Set A is a superset of another set B if every member of B is also a member of A.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let attendees = ["Alicia", "Bethany", "Diana"]
print(employees.isSuperset(of: attendees))
// Prints "true"
  • Parameter possibleSubset: A sequence of elements. possibleSubset must be finite.

Declaration

@inlinable public func isSuperset<S>(of possibleSubset: S) -> Bool where Element == S.Element, S: Sequence
func isSuperset(of other: Set<Element>) -> Bool Required

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

Set A is a superset of another set B if every member of B is also a member of A.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let attendees: Set = ["Alicia", "Bethany", "Diana"]
print(employees.isSuperset(of: attendees))
// Prints "true"
  • Parameter other: Another set.

Declaration

@inlinable public func isSuperset(of other: Set<Element>) -> Bool
func isSuperset(of other: Self) -> Bool Required

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

Set A is a superset of another set B if every member of B is also a member of A.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let attendees: Set = ["Alicia", "Bethany", "Diana"]
print(employees.isSuperset(of: attendees))
// Prints "true"
  • Parameter other: A set of the same type as the current set.

Declaration

@inlinable public func isSuperset(of other: Self) -> Bool
func lexicographicallyPrecedes(_ other: OtherSequence, by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool) rethrows -> Bool Required

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

The predicate must be a strict weak ordering over the elements. That is, for any elements a, b, and c, the following conditions must hold:

Note: This method implements the mathematical notion of lexicographical ordering, which has no connection to Unicode. If you are sorting strings to present to the end user, use String APIs that perform localized comparison instead.

Complexity: O(m), where m is the lesser of the length of the sequence and the length of other.

Declaration

@inlinable public func lexicographicallyPrecedes<OtherSequence>(_ other: OtherSequence, by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool) rethrows -> Bool where OtherSequence: Sequence, Self.Element == OtherSequence.Element
func makeIterator() -> Set<Element>.Iterator Required

Returns an iterator over the members of the set.

Declaration

@inlinable public func makeIterator() -> Set<Element>.Iterator
func map(_ transform: (Self.Element) throws -> T) rethrows -> [T] Required

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

In this example, map is used first to convert the names in the array to lowercase strings and then to count their characters.

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let lowercaseNames = cast.map { $0.lowercased() }
// 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
let letterCounts = cast.map { $0.count }
// 'letterCounts' == [6, 6, 3, 4]
  • Parameter transform: A mapping closure. transform accepts an element of this sequence as its parameter and returns a transformed value of the same or of a different type.

Complexity: O(n), where n is the length of the sequence.

Declaration

@inlinable public func map<T>(_ transform: (Self.Element) throws -> T) rethrows -> [T]
func map(_ transform: (Self.Element) throws -> T) rethrows -> [T] Required

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

In this example, map is used first to convert the names in the array to lowercase strings and then to count their characters.

let cast = ["Vivien", "Marlon", "Kim", "Karl"]
let lowercaseNames = cast.map { $0.lowercased() }
// 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"]
let letterCounts = cast.map { $0.count }
// 'letterCounts' == [6, 6, 3, 4]
  • Parameter transform: A mapping closure. transform accepts an element of this sequence as its parameter and returns a transformed value of the same or of a different type.

Declaration

@inlinable public func map<T>(_ transform: (Self.Element) throws -> T) rethrows -> [T]
func max(by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool) rethrows -> Self.Element? Required

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

The predicate must be a strict weak ordering over the elements. That is, for any elements a, b, and c, the following conditions must hold:

This example shows how to use the max(by:) method on a dictionary to find the key-value pair with the highest value.

let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
let greatestHue = hues.max { a, b in a.value < b.value }
print(greatestHue)
// Prints "Optional(("Heliotrope", 296))"
  • Parameter areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false.

Complexity: O(n), where n is the length of the sequence.

Declaration

@warn_unqualified_access @inlinable public func max(by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool) rethrows -> Self.Element?
func min(by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool) rethrows -> Self.Element? Required

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

The predicate must be a strict weak ordering over the elements. That is, for any elements a, b, and c, the following conditions must hold:

This example shows how to use the min(by:) method on a dictionary to find the key-value pair with the lowest value.

let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
let leastHue = hues.min { a, b in a.value < b.value }
print(leastHue)
// Prints "Optional(("Coral", 16))"
  • Parameter areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false.

Complexity: O(n), where n is the length of the sequence.

Declaration

@warn_unqualified_access @inlinable public func min(by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool) rethrows -> Self.Element?
func popFirst() -> Element? Required

Removes and returns the first element of the set.

Because a set is not an ordered collection, the "first" element may not be the first element that was added to the set.

Declaration

@inlinable public mutating func popFirst() -> Element?
func prefix(_ maxLength: Int) -> PrefixSequence<Self> Required

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

If the maximum length exceeds the number of elements in the sequence, the result contains all the elements in the sequence.

let numbers = [1, 2, 3, 4, 5]
print(numbers.prefix(2))
// Prints "[1, 2]"
print(numbers.prefix(10))
// Prints "[1, 2, 3, 4, 5]"
  • Parameter maxLength: The maximum number of elements to return. The value of maxLength must be greater than or equal to zero.

Complexity: O(1)

Declaration

@inlinable public func prefix(_ maxLength: Int) -> PrefixSequence<Self>
func prefix(_ maxLength: Int) -> Self.SubSequence Required

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

If the maximum length exceeds the number of elements in the collection, the result contains all the elements in the collection.

let numbers = [1, 2, 3, 4, 5]
print(numbers.prefix(2))
// Prints "[1, 2]"
print(numbers.prefix(10))
// Prints "[1, 2, 3, 4, 5]"
  • Parameter maxLength: The maximum number of elements to return. maxLength must be greater than or equal to zero.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(k), where k is the number of elements to select from the beginning of the collection.

Declaration

@inlinable public func prefix(_ maxLength: Int) -> Self.SubSequence
func prefix(through position: Self.Index) -> Self.SubSequence Required

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

The resulting subsequence includes the element at the position end. The following example searches for the index of the number 40 in an array of integers, and then prints the prefix of the array up to, and including, that index:

let numbers = [10, 20, 30, 40, 50, 60]
if let i = numbers.firstIndex(of: 40) {
    print(numbers.prefix(through: i))
}
// Prints "[10, 20, 30, 40]"

Using the prefix(through:) method is equivalent to using a partial closed range as the collection's subscript. The subscript notation is preferred over prefix(through:).

if let i = numbers.firstIndex(of: 40) {
    print(numbers[...i])
}
// Prints "[10, 20, 30, 40]"
  • Parameter end: The index of the last element to include in the resulting subsequence. end must be a valid index of the collection that is not equal to the endIndex property.

Complexity: O(1)

Declaration

@inlinable public func prefix(through position: Self.Index) -> Self.SubSequence
func prefix(upTo end: Self.Index) -> Self.SubSequence Required

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

The resulting subsequence does not include the element at the position end. The following example searches for the index of the number 40 in an array of integers, and then prints the prefix of the array up to, but not including, that index:

let numbers = [10, 20, 30, 40, 50, 60]
if let i = numbers.firstIndex(of: 40) {
    print(numbers.prefix(upTo: i))
}
// Prints "[10, 20, 30]"

Passing the collection's starting index as the end parameter results in an empty subsequence.

print(numbers.prefix(upTo: numbers.startIndex))
// Prints "[]"

Using the prefix(upTo:) method is equivalent to using a partial half-open range as the collection's subscript. The subscript notation is preferred over prefix(upTo:).

if let i = numbers.firstIndex(of: 40) {
    print(numbers[..<i])
}
// Prints "[10, 20, 30]"
  • Parameter end: The "past the end" index of the resulting subsequence. end must be a valid index of the collection.

Complexity: O(1)

Declaration

@inlinable public func prefix(upTo end: Self.Index) -> Self.SubSequence
func prefix(while predicate: (Self.Element) throws -> Bool) rethrows -> [Self.Element] Required

Returns a sequence containing the initial, consecutive elements that satisfy the given predicate.

The following example uses the prefix(while:) method to find the positive numbers at the beginning of the numbers array. Every element of numbers up to, but not including, the first negative value is included in the result.

let numbers = [3, 7, 4, -2, 9, -6, 10, 1]
let positivePrefix = numbers.prefix(while: { $0 > 0 })
// positivePrefix == [3, 7, 4]

If predicate matches every element in the sequence, the resulting sequence contains every element of the sequence.

  • Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the result.

Complexity: O(k), where k is the length of the result.

Declaration

@inlinable public func prefix(while predicate: (Self.Element) throws -> Bool) rethrows -> [Self.Element]
func prefix(while predicate: (Self.Element) throws -> Bool) rethrows -> Self.SubSequence Required

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

  • Parameter predicate: A closure that takes an element of the sequence as its argument and returns true if the element should be included or false if it should be excluded. Once the predicate returns false it will not be called again.

Complexity: O(n), where n is the length of the collection.

Declaration

@inlinable public func prefix(while predicate: (Self.Element) throws -> Bool) rethrows -> Self.SubSequence
func randomElement() -> Self.Element? Required

Returns a random element of the collection.

Call randomElement() to select a random element from an array or another collection. This example picks a name at random from an array:

let names = ["Zoey", "Chloe", "Amani", "Amaia"]
let randomName = names.randomElement()!
// randomName == "Amani"

This method is equivalent to calling randomElement(using:), passing in the system's default random generator.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.

Declaration

@inlinable public func randomElement() -> Self.Element?
func randomElement(using generator: inout T) -> Self.Element? Required

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

Call randomElement(using:) to select a random element from an array or another collection when you are using a custom random number generator. This example picks a name at random from an array:

let names = ["Zoey", "Chloe", "Amani", "Amaia"]
let randomName = names.randomElement(using: &myGenerator)!
// randomName == "Amani"
  • Parameter generator: The random number generator to use when choosing a random element.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.

Note: The algorithm used to select a random element may change in a future version of Swift. If you're passing a generator that results in the same sequence of elements each time you run your program, that sequence may change when your program is compiled using a different version of Swift.

Declaration

@inlinable public func randomElement<T>(using generator: inout T) -> Self.Element? where T: RandomNumberGenerator
func reduce(_ initialResult: Result, _ nextPartialResult: (Result, Self.Element) throws -> Result) rethrows -> Result Required

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

Use the reduce(_:_:) method to produce a single value from the elements of an entire sequence. For example, you can use this method on an array of numbers to find their sum or product.

The nextPartialResult closure is called sequentially with an accumulating value initialized to initialResult and each element of the sequence. This example shows how to find the sum of an array of numbers.

let numbers = [1, 2, 3, 4]
let numberSum = numbers.reduce(0, { x, y in
    x + y
})
// numberSum == 10

When numbers.reduce(_:_:) is called, the following steps occur:

  1. The nextPartialResult closure is called with initialResult---0 in this case---and the first element of numbers, returning the sum: 1.
  2. The closure is called again repeatedly with the previous call's return value and each element of the sequence.
  3. When the sequence is exhausted, the last value returned from the closure is returned to the caller.

If the sequence has no elements, nextPartialResult is never executed and initialResult is the result of the call to reduce(_:_:).

Complexity: O(n), where n is the length of the sequence.

Declaration

@inlinable public func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Self.Element) throws -> Result) rethrows -> Result
func reduce(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Self.Element) throws -> ()) rethrows -> Result Required

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

Use the reduce(into:_:) method to produce a single value from the elements of an entire sequence. For example, you can use this method on an array of integers to filter adjacent equal entries or count frequencies.

This method is preferred over reduce(_:_:) for efficiency when the result is a copy-on-write type, for example an Array or a Dictionary.

The updateAccumulatingResult closure is called sequentially with a mutable accumulating value initialized to initialResult and each element of the sequence. This example shows how to build a dictionary of letter frequencies of a string.

let letters = "abracadabra"
let letterCount = letters.reduce(into: [:]) { counts, letter in
    counts[letter, default: 0] += 1
}
// letterCount == ["a": 5, "b": 2, "r": 2, "c": 1, "d": 1]

When letters.reduce(into:_:) is called, the following steps occur:

  1. The updateAccumulatingResult closure is called with the initial accumulating value---[:] in this case---and the first character of letters, modifying the accumulating value by setting 1 for the key "a".
  2. The closure is called again repeatedly with the updated accumulating value and each element of the sequence.
  3. When the sequence is exhausted, the accumulating value is returned to the caller.

If the sequence has no elements, updateAccumulatingResult is never executed and initialResult is the result of the call to reduce(into:_:).

Complexity: O(n), where n is the length of the sequence.

Declaration

@inlinable public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Self.Element) throws -> ()) rethrows -> Result
func remove(_ member: Element) -> Element? Required

Removes the specified element from the set.

This example removes the element "sugar" from a set of ingredients.

var ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]
let toRemove = "sugar"
if let removed = ingredients.remove(toRemove) {
    print("The recipe is now \(removed)-free.")
}
// Prints "The recipe is now sugar-free."
  • Parameter member: The element to remove from the set.

Declaration

@inlinable public mutating func remove(_ member: Element) -> Element?
func remove(at position: Set<Element>.Index) -> Element Required

Removes the element at the given index of the set.

  • Parameter position: The index of the member to remove. position must be a valid index of the set, and must not be equal to the set's end index.

Declaration

@inlinable public mutating func remove(at position: Set<Element>.Index) -> Element
func removeAll(keepingCapacity keepCapacity: Bool = false) Required

Removes all members from the set.

  • Parameter keepingCapacity: If true, the set's buffer capacity is preserved; if false, the underlying buffer is released. The default is false.

Declaration

@inlinable public mutating func removeAll(keepingCapacity keepCapacity: Bool = false)
func removeFirst() -> Element Required

Removes the first element of the set.

Because a set is not an ordered collection, the "first" element may not be the first element that was added to the set. The set must not be empty.

Complexity: Amortized O(1) if the set does not wrap a bridged NSSet. If the set wraps a bridged NSSet, the performance is unspecified.

Declaration

@inlinable public mutating func removeFirst() -> Element
func reserveCapacity(_ minimumCapacity: Int) Required

Reserves enough space to store the specified number of elements.

If you are adding a known number of elements to a set, use this method to avoid multiple reallocations. This method ensures that the set has unique, mutable, contiguous storage, with space allocated for at least the requested number of elements.

Calling the reserveCapacity(_:) method on a set with bridged storage triggers a copy to contiguous storage even if the existing storage has room to store minimumCapacity elements.

  • Parameter minimumCapacity: The requested number of elements to store.

Declaration

public mutating func reserveCapacity(_ minimumCapacity: Int)
func reversed() -> [Self.Element] Required

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

The sequence must be finite.

Complexity: O(n), where n is the length of the sequence.

Declaration

@inlinable public func reversed() -> [Self.Element]
func shuffled() -> [Self.Element] Required

Returns the elements of the sequence, shuffled.

For example, you can shuffle the numbers between 0 and 9 by calling the shuffled() method on that range:

let numbers = 0...9
let shuffledNumbers = numbers.shuffled()
// shuffledNumbers == [1, 7, 6, 2, 8, 9, 4, 3, 5, 0]

This method is equivalent to calling shuffled(using:), passing in the system's default random generator.

Complexity: O(n), where n is the length of the sequence.

Declaration

@inlinable public func shuffled() -> [Self.Element]
func shuffled(using generator: inout T) -> [Self.Element] Required

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

You use this method to randomize the elements of a sequence when you are using a custom random number generator. For example, you can shuffle the numbers between 0 and 9 by calling the shuffled(using:) method on that range:

let numbers = 0...9
let shuffledNumbers = numbers.shuffled(using: &myGenerator)
// shuffledNumbers == [8, 9, 4, 3, 2, 6, 7, 0, 5, 1]
  • Parameter generator: The random number generator to use when shuffling the sequence.

Complexity: O(n), where n is the length of the sequence.

Note: The algorithm used to shuffle a sequence may change in a future version of Swift. If you're passing a generator that results in the same shuffled order each time you run your program, that sequence may change when your program is compiled using a different version of Swift.

Declaration

@inlinable public func shuffled<T>(using generator: inout T) -> [Self.Element] where T: RandomNumberGenerator
func sorted(by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool) rethrows -> [Self.Element] Required

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

When you want to sort a sequence of elements that don't conform to the Comparable protocol, pass a predicate to this method that returns true when the first element should be ordered before the second. The elements of the resulting array are ordered according to the given predicate.

In the following example, the predicate provides an ordering for an array of a custom HTTPResponse type. The predicate orders errors before successes and sorts the error responses by their error code.

enum HTTPResponse {
    case ok
    case error(Int)
}

let responses: [HTTPResponse] = [.error(500), .ok, .ok, .error(404), .error(403)]
let sortedResponses = responses.sorted {
    switch ($0, $1) {
    // Order errors by code
    case let (.error(aCode), .error(bCode)):
        return aCode < bCode

    // All successes are equivalent, so none is before any other
    case (.ok, .ok): return false

    // Order errors before successes
    case (.error, .ok): return true
    case (.ok, .error): return false
    }
}
print(sortedResponses)
// Prints "[.error(403), .error(404), .error(500), .ok, .ok]"

You also use this method to sort elements that conform to the Comparable protocol in descending order. To sort your sequence in descending order, pass the greater-than operator (>) as the areInIncreasingOrder parameter.

let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
let descendingStudents = students.sorted(by: >)
print(descendingStudents)
// Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]"

Calling the related sorted() method is equivalent to calling this method and passing the less-than operator (<) as the predicate.

print(students.sorted())
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
print(students.sorted(by: <))
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"

The predicate must be a strict weak ordering over the elements. That is, for any elements a, b, and c, the following conditions must hold:

The sorting algorithm is not guaranteed to be stable. A stable sort preserves the relative order of elements for which areInIncreasingOrder does not establish an order.

  • Parameter areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false.

Complexity: O(n log n), where n is the length of the sequence.

Declaration

@inlinable public func sorted(by areInIncreasingOrder: (Self.Element, Self.Element) throws -> Bool) rethrows -> [Self.Element]
func split(maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Self.Element) throws -> Bool) rethrows -> [ArraySlice<Self.Element>] Required

Returns the longest possible subsequences of the sequence, in order, that don't contain elements satisfying the given predicate. Elements that are used to split the sequence are not returned as part of any subsequence.

The following examples show the effects of the maxSplits and omittingEmptySubsequences parameters when splitting a string using a closure that matches spaces. The first use of split returns each word that was originally separated by one or more spaces.

let line = "BLANCHE:   I don't want realism. I want magic!"
print(line.split(whereSeparator: { $0 == " " })
          .map(String.init))
// Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

The second example passes 1 for the maxSplits parameter, so the original string is split just once, into two new strings.

print(
   line.split(maxSplits: 1, whereSeparator: { $0 == " " })
                  .map(String.init))
// Prints "["BLANCHE:", "  I don\'t want realism. I want magic!"]"

The final example passes true for the allowEmptySlices parameter, so the returned array contains empty strings where spaces were repeated.

print(
    line.split(
        omittingEmptySubsequences: false,
        whereSeparator: { $0 == " " }
    ).map(String.init))
// Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

Complexity: O(n), where n is the length of the sequence.

Declaration

@inlinable public func split(maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Self.Element) throws -> Bool) rethrows -> [ArraySlice<Self.Element>]
func split(maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Self.Element) throws -> Bool) rethrows -> [Self.SubSequence] Required

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

The resulting array consists of at most maxSplits + 1 subsequences. Elements that are used to split the sequence are not returned as part of any subsequence.

The following examples show the effects of the maxSplits and omittingEmptySubsequences parameters when splitting a string using a closure that matches spaces. The first use of split returns each word that was originally separated by one or more spaces.

let line = "BLANCHE:   I don't want realism. I want magic!"
print(line.split(whereSeparator: { $0 == " " }))
// Prints "["BLANCHE:", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

The second example passes 1 for the maxSplits parameter, so the original string is split just once, into two new strings.

print(line.split(maxSplits: 1, whereSeparator: { $0 == " " }))
// Prints "["BLANCHE:", "  I don\'t want realism. I want magic!"]"

The final example passes false for the omittingEmptySubsequences parameter, so the returned array contains empty strings where spaces were repeated.

print(line.split(omittingEmptySubsequences: false, whereSeparator: { $0 == " " }))
// Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]"

Complexity: O(n), where n is the length of the collection.

Declaration

@inlinable public func split(maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true, whereSeparator isSeparator: (Self.Element) throws -> Bool) rethrows -> [Self.SubSequence]
func starts(with possiblePrefix: PossiblePrefix, by areEquivalent: (Self.Element, PossiblePrefix.Element) throws -> Bool) rethrows -> Bool Required

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.

The predicate must be a equivalence relation over the elements. That is, for any elements a, b, and c, the following conditions must hold:

Complexity: O(m), where m is the lesser of the length of the sequence and the length of possiblePrefix.

Declaration

@inlinable public func starts<PossiblePrefix>(with possiblePrefix: PossiblePrefix, by areEquivalent: (Self.Element, PossiblePrefix.Element) throws -> Bool) rethrows -> Bool where PossiblePrefix: Sequence
func subtract(_ other: S) Required

Removes the elements of the given sequence from the set.

In the following example, the elements of the employees set that are also elements of the neighbors array are removed. In particular, the names "Bethany" and "Eric" are removed from employees.

var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let neighbors = ["Bethany", "Eric", "Forlani", "Greta"]
employees.subtract(neighbors)
print(employees)
// Prints "["Chris", "Diana", "Alicia"]"
  • Parameter other: A sequence of elements. other must be finite.

Declaration

@inlinable public mutating func subtract<S>(_ other: S) where Element == S.Element, S: Sequence
func subtract(_ other: Set<Element>) Required

Removes the elements of the given set from this set.

In the following example, the elements of the employees set that are also members of the neighbors set are removed. In particular, the names "Bethany" and "Eric" are removed from employees.

var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
employees.subtract(neighbors)
print(employees)
// Prints "["Diana", "Chris", "Alicia"]"
  • Parameter other: Another set.

Declaration

@inlinable public mutating func subtract(_ other: Set<Element>)
func subtract(_ other: Self) Required

Removes the elements of the given set from this set.

In the following example, the elements of the employees set that are also members of the neighbors set are removed. In particular, the names "Bethany" and "Eric" are removed from employees.

var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
employees.subtract(neighbors)
print(employees)
// Prints "["Diana", "Chris", "Alicia"]"
  • Parameter other: A set of the same type as the current set.

Declaration

@inlinable public mutating func subtract(_ other: Self)
func subtracting(_ other: S) -> Set<Element> Required

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

In the following example, the nonNeighbors set is made up of the elements of the employees set that are not elements of neighbors:

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let neighbors = ["Bethany", "Eric", "Forlani", "Greta"]
let nonNeighbors = employees.subtracting(neighbors)
print(nonNeighbors)
// Prints "["Chris", "Diana", "Alicia"]"
  • Parameter other: A sequence of elements. other must be finite.

Declaration

@inlinable public func subtracting<S>(_ other: S) -> Set<Element> where Element == S.Element, S: Sequence
func subtracting(_ other: Set<Element>) -> Set<Element> Required

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

In the following example, the nonNeighbors set is made up of the elements of the employees set that are not elements of neighbors:

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
let nonNeighbors = employees.subtracting(neighbors)
print(nonNeighbors)
// Prints "["Diana", "Chris", "Alicia"]"
  • Parameter other: Another set.

Declaration

@inlinable public func subtracting(_ other: Set<Element>) -> Set<Element>
func subtracting(_ other: Self) -> Self Required

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

In the following example, the nonNeighbors set is made up of the elements of the employees set that are not elements of neighbors:

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
let nonNeighbors = employees.subtract(neighbors)
print(nonNeighbors)
// Prints "["Diana", "Chris", "Alicia"]"
  • Parameter other: A set of the same type as the current set.

Declaration

@inlinable public func subtracting(_ other: Self) -> Self
func suffix(_ maxLength: Int) -> [Self.Element] Required

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

The sequence must be finite. If the maximum length exceeds the number of elements in the sequence, the result contains all the elements in the sequence.

let numbers = [1, 2, 3, 4, 5]
print(numbers.suffix(2))
// Prints "[4, 5]"
print(numbers.suffix(10))
// Prints "[1, 2, 3, 4, 5]"
  • Parameter maxLength: The maximum number of elements to return. The value of maxLength must be greater than or equal to zero.

Complexity: O(n), where n is the length of the sequence.

Declaration

@inlinable public func suffix(_ maxLength: Int) -> [Self.Element]
func suffix(_ maxLength: Int) -> Self.SubSequence Required

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

If the maximum length exceeds the number of elements in the collection, the result contains all the elements in the collection.

let numbers = [1, 2, 3, 4, 5]
print(numbers.suffix(2))
// Prints "[4, 5]"
print(numbers.suffix(10))
// Prints "[1, 2, 3, 4, 5]"
  • Parameter maxLength: The maximum number of elements to return. The value of maxLength must be greater than or equal to zero.

Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the length of the collection.

Declaration

@inlinable public func suffix(_ maxLength: Int) -> Self.SubSequence
func suffix(from start: Self.Index) -> Self.SubSequence Required

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

The following example searches for the index of the number 40 in an array of integers, and then prints the suffix of the array starting at that index:

let numbers = [10, 20, 30, 40, 50, 60]
if let i = numbers.firstIndex(of: 40) {
    print(numbers.suffix(from: i))
}
// Prints "[40, 50, 60]"

Passing the collection's endIndex as the start parameter results in an empty subsequence.

print(numbers.suffix(from: numbers.endIndex))
// Prints "[]"

Using the suffix(from:) method is equivalent to using a partial range from the index as the collection's subscript. The subscript notation is preferred over suffix(from:).

if let i = numbers.firstIndex(of: 40) {
    print(numbers[i...])
}
// Prints "[40, 50, 60]"
  • Parameter start: The index at which to start the resulting subsequence. start must be a valid index of the collection.

Complexity: O(1)

Declaration

@inlinable public func suffix(from start: Self.Index) -> Self.SubSequence
func symmetricDifference(_ other: S) -> Set<Element> Required

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

In the following example, the eitherNeighborsOrEmployees set is made up of the elements of the employees and neighbors sets that are not in both employees and neighbors. In particular, the names "Bethany" and "Eric" do not appear in eitherNeighborsOrEmployees.

let employees: Set = ["Alicia", "Bethany", "Diana", "Eric"]
let neighbors = ["Bethany", "Eric", "Forlani"]
let eitherNeighborsOrEmployees = employees.symmetricDifference(neighbors)
print(eitherNeighborsOrEmployees)
// Prints "["Diana", "Forlani", "Alicia"]"
  • Parameter other: A sequence of elements. other must be finite.

Declaration

@inlinable public func symmetricDifference<S>(_ other: S) -> Set<Element> where Element == S.Element, S: Sequence
func union(_ other: S) -> Set<Element> Required

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

In the following example, the attendeesAndVisitors set is made up of the elements of the attendees set and the visitors array:

let attendees: Set = ["Alicia", "Bethany", "Diana"]
let visitors = ["Marcia", "Nathaniel"]
let attendeesAndVisitors = attendees.union(visitors)
print(attendeesAndVisitors)
// Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"

If the set already contains one or more elements that are also in other, the existing members are kept. If other contains multiple instances of equivalent elements, only the first instance is kept.

let initialIndices = Set(0..<5)
let expandedIndices = initialIndices.union([2, 3, 6, 6, 7, 7])
print(expandedIndices)
// Prints "[2, 4, 6, 7, 0, 1, 3]"
  • Parameter other: A sequence of elements. other must be finite.

Declaration

@inlinable public func union<S>(_ other: S) -> Set<Element> where Element == S.Element, S: Sequence
func update(with newMember: Element) -> Element? Required

Inserts the given element into the set unconditionally.

If an element equal to newMember is already contained in the set, newMember replaces the existing element. In this example, an existing element is inserted into classDays, a set of days of the week.

enum DayOfTheWeek: Int {
    case sunday, monday, tuesday, wednesday, thursday,
        friday, saturday
}

var classDays: Set<DayOfTheWeek> = [.monday, .wednesday, .friday]
print(classDays.update(with: .monday))
// Prints "Optional(.monday)"
  • Parameter newMember: An element to insert into the set.

Declaration

@inlinable public mutating func update(with newMember: Element) -> Element?
func withContiguousStorageIfAvailable(_ body: (UnsafeBufferPointer<Self.Element>) throws -> R) rethrows -> R? Required

Call body(p), where p is a pointer to the collection's contiguous storage. If no such storage exists, it is first created. If the collection does not support an internal representation in a form of contiguous storage, body is not called and nil is returned.

A Collection that provides its own implementation of this method must also guarantee that an equivalent buffer of its SubSequence can be generated by advancing the pointer by the distance to the slice's startIndex.

Declaration

@inlinable public func withContiguousStorageIfAvailable<R>(_ body: (UnsafeBufferPointer<Self.Element>) throws -> R) rethrows -> R?

Type Methods

func !=(lhs: Self, rhs: Self) -> Bool Required

Declaration

public static func !=(lhs: Self, rhs: Self) -> Bool
func ==(lhs: Set<Element>, rhs: Set<Element>) -> Bool Required

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

Declaration

@inlinable public static func ==(lhs: Set<Element>, rhs: Set<Element>) -> Bool