struct Set<Element : Hashable> An unordered collection of unique elements. You use a set instead of an array when you need to test efficiently for membership and you aren't concerned with the order of the elements in the collection, or when you need to ensure that each element appears only once in a collection. You can create a set with any element type that conforms to the Hashable protocol. By default, most types in the standard library are hashable, including strings, numeric and Boolean types, enumeration cases without associated values, and even sets themselves. Swift makes it as easy to create a new set as to create a new array. Simply assign an array literal to a variable or constant with the Set type specified. let ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"] if ingredients.contains("sugar") { print("No thanks, too sweet.") } // Prints "No thanks, too sweet." Set Operations Sets provide a suite of mathematical set operations. For example, you can efficiently test a set for membership of an element or check its intersection with another set: Use the contains(_:) method to test whether a set contains a specific element. Use the "equal to" operator (==) to test whether two sets contain the same elements. Use the isSubset(of:) method to test whether a set contains all the elements of another set or sequence. Use the isSuperset(of:) method to test whether all elements of a set are contained in another set or sequence. Use the isStrictSubset(of:) and isStrictSuperset(of:) methods to test whether a set is a subset or superset of, but not equal to, another set. Use the isDisjoint(with:) method to test whether a set has any elements in common with another set. You can also combine, exclude, or subtract the elements of two sets: Use the union(_:) method to create a new set with the elements of a set and another set or sequence. Use the intersection(_:) method to create a new set with only the elements common to a set and another set or sequence. Use the symmetricDifference(_:) method to create a new set with the elements that are in either a set or another set or sequence, but not in both. Use the subtracting(_:) method to create a new set with the elements of a set that are not also in another set or sequence. You can modify a set in place by using these methods' mutating counterparts: formUnion(_:), formIntersection(_:), formSymmetricDifference(_:), and subtract(_:). Set operations are not limited to use with other sets. Instead, you can perform set operations with another set, an array, or any other sequence type. var primes: Set = [2, 3, 5, 7] // Tests whether primes is a subset of a Range<Int> print(primes.isSubset(of: 0..<10)) // Prints "true" // Performs an intersection with an Array<Int> let favoriteNumbers = [5, 7, 15, 21] print(primes.intersection(favoriteNumbers)) // Prints "[5, 7]" Sequence and Collection Operations In addition to the Set type's set operations, you can use any nonmutating sequence or collection methods with a set. if primes.isEmpty { print("No primes!") } else { print("We have \(primes.count) primes.") } // Prints "We have 4 primes." let primesSum = primes.reduce(0, +) // 'primesSum' == 17 let primeStrings = primes.sorted().map(String.init) // 'primeStrings' == ["2", "3", "5", "7"] You can iterate through a set's unordered elements with a for-in loop. for number in primes { print(number) } // Prints "5" // Prints "7" // Prints "2" // Prints "3" Many sequence and collection operations return an array or a type-erasing collection wrapper instead of a set. To restore efficient set operations, create a new set from the result. let morePrimes = primes.union([11, 13, 17, 19]) let laterPrimes = morePrimes.filter { $0 > 10 } // 'laterPrimes' is of type Array<Int> let laterPrimesSet = Set(morePrimes.filter { $0 > 10 }) // 'laterPrimesSet' is of type Set<Int> Bridging Between Set and NSSet You can bridge between Set and NSSet using the as operator. For bridging to be possible, the Element type of a set must be a class, an @objc protocol (a protocol imported from Objective-C or marked with the @objc attribute), or a type that bridges to a Foundation type. Bridging from Set to NSSet always takes O(1) time and space. When the set's Element type is neither a class nor an @objc protocol, any required bridging of elements occurs at the first access of each element, so the first operation that uses the contents of the set (for example, a membership test) can take O(n). Bridging from NSSet to Set first calls the copy(with:) method (**copyWithZone:** in Objective-C) on the set to get an immutable copy and then performs additional Swift bookkeeping work that takes O(1) time. For instances of NSSet that are already immutable, copy(with:) returns the same set in constant time; otherwise, the copying performance is unspecified. The instances of NSSet and Set share storage using the same copy-on-write optimization that is used when two instances of Set share storage. See Also: Hashable Inheritance Collection, CustomDebugStringConvertible, CustomReflectable, CustomStringConvertible, Equatable, ExpressibleByArrayLiteral, Hashable, Indexable, IndexableBase, Sequence, SetAlgebra View Protocol Hierarchy → Associated Types Index = SetIndex<Element> The index type for subscripting the set. Iterator = SetIterator<Element> Type alias inferred. Element = Element Type alias inferred. Index = SetIndex<Element> Type alias inferred. SubSequence = Slice<Set<Element>> Type alias inferred. Import import Swift Initializers init() 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 init() init(_:) 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]" sequence: The elements to use as members of the new set. Declaration init<Source : Sequence where Source.Iterator.Element == Element>(_ sequence: Source) Declared In Set , SetAlgebra init(arrayLiteral:) 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!" elements: A variadic list of elements of the new set. Declaration init(arrayLiteral elements: Element...) Declared In Set , SetAlgebra init(minimumCapacity:) Creates a new, empty set with at least the specified number of elements' worth of storage. Use this initializer to avoid repeated reallocations of a set's storage if you know you'll be adding elements to the set after creation. The actual capacity of the created set will be the smallest power of 2 that is greater than or equal to minimumCapacity. minimumCapacity: The minimum number of elements that the newly created set should be able to store without reallocating its storage. Declaration init(minimumCapacity: Int) Instance Variables var count: Int The number of elements in the set. Declaration var count: Int { get } var customMirror: Mirror A mirror that reflects the set. Declaration var customMirror: Mirror { get } var debugDescription: String A string that represents the contents of the set, suitable for debugging. Declaration var debugDescription: String { get } var description: String A string that represents the contents of the set. Declaration var description: String { get } var endIndex: SetIndex<Element> 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: SetIndex<Element> { get } var first: Element? The first element of the set. The first element of the set is not necessarily the first element added to the set. Don't expect any particular ordering of set elements. If the set is empty, the value of this property is nil. Declaration var first: Element? { get } Declared In Set , Collection var hashValue: Int The hash value for the set. Two sets that are equal will always have equal hash values. Hash values are not guaranteed to be equal across different executions of your program. Do not save hash values to use during a future execution. Declaration var hashValue: Int { get } var isEmpty: Bool A Boolean value that indicates whether the set is empty. Declaration var isEmpty: Bool { get } Declared In Set , SetAlgebra , Collection var lazy: LazyCollection<Set<Element>> A view onto this collection that provides lazy implementations of normally eager operations, such as map and filter. Use the lazy property when chaining operations to prevent intermediate operations from allocating storage, or when you only need a part of the final collection to avoid unnecessary computation. See Also: LazySequenceProtocol, LazyCollectionProtocol. Declaration var lazy: LazyCollection<Set<Element>> { get } Declared In Collection var startIndex: SetIndex<Element> The starting position for iterating members of the set. If the set is empty, startIndex is equal to endIndex. Declaration var startIndex: SetIndex<Element> { get } var underestimatedCount: Int 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 { get } Declared In Collection , Sequence Subscripts subscript(_: ClosedRange<SetIndex<Element>>) Accesses a contiguous subrange of the collection's elements. The accessed slice uses the same indices for the same elements as the original collection. Always use the slice's startIndex property instead of assuming that its indices start at a particular value. This example demonstrates getting a slice of an array of strings, finding the index of one of the strings in the slice, and then using that index in the original array. let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] let streetsSlice = streets[2 ..< streets.endIndex] print(streetsSlice) // Prints "["Channing", "Douglas", "Evarts"]" let index = streetsSlice.index(of: "Evarts") // 4 print(streets[index!]) // Prints "Evarts" bounds: A range of the collection's indices. The bounds of the range must be valid indices of the collection. Declaration subscript(bounds: ClosedRange<SetIndex<Element>>) -> Slice<Set<Element>> { get } Declared In Collection, Indexable subscript(_: Range<SetIndex<Element>>) Accesses a contiguous subrange of the collection's elements. The accessed slice uses the same indices for the same elements as the original collection uses. Always use the slice's startIndex property instead of assuming that its indices start at a particular value. This example demonstrates getting a slice of an array of strings, finding the index of one of the strings in the slice, and then using that index in the original array. let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] let streetsSlice = streets[2 ..< streets.endIndex] print(streetsSlice) // Prints "["Channing", "Douglas", "Evarts"]" let index = streetsSlice.index(of: "Evarts") // 4 print(streets[index!]) // Prints "Evarts" bounds: A range of the collection's indices. The bounds of the range must be valid indices of the collection. Declaration subscript(bounds: Range<SetIndex<Element>>) -> Slice<Set<Element>> { get } Declared In Collection subscript(_: SetIndex<Element>) Accesses the member at the given position. Declaration subscript(position: SetIndex<Element>) -> Element { get } Instance Methods func ==(_:rhs:) Returns a Boolean value indicating whether two sets have equal elements. Parameters: lhs: A set. rhs: Another set. Returns: true if the lhs and rhs have the same elements; otherwise, false. Declaration func ==(lhs: Set<Element>, rhs: Set<Element>) -> Bool func contains(_:) 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!" member: An element to look for in the set. Returns: true if member exists in the set; otherwise, false. Declaration func contains(_ member: Element) -> Bool Declared In Set, Collection, Sequence func contains(where:) 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 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. Returns: true if the sequence contains an element that satisfies predicate; otherwise, false. Declaration func contains(where predicate: (Element) throws -> Bool) rethrows -> Bool Declared In Collection, Sequence func distance(from:to:) Returns the distance between two indices. Unless the collection conforms to the BidirectionalCollection protocol, start must be less than or equal to end. Parameters: start: A valid index of the collection. end: Another valid index of the collection. If end is equal to start, the result is zero. Returns: The distance between start and end. The result can be negative only if the collection conforms to the BidirectionalCollection protocol. Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the resulting distance. Declaration func distance(from start: SetIndex<Element>, to end: SetIndex<Element>) -> SetIndex<Element>Distance Declared In Collection, Indexable func dropFirst() Returns a subsequence containing all but the first element of the sequence. The following example drops the first element from an array of integers. let numbers = [1, 2, 3, 4, 5] print(numbers.dropFirst()) // Prints "[2, 3, 4, 5]" If the sequence has no elements, the result is an empty subsequence. let empty: [Int] = [] print(empty.dropFirst()) // Prints "[]" Returns: A subsequence starting after the first element of the sequence. Complexity: O(1) Declaration func dropFirst() -> Slice<Set<Element>> Declared In Collection, Sequence func dropFirst(_:) 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 "[]" n: The number of elements to drop from the beginning of the collection. n must be greater than or equal to zero. Returns: A subsequence starting after the specified number of elements. Complexity: O(n), where n is the number of elements to drop from the beginning of the collection. Declaration func dropFirst(_ n: Int) -> Slice<Set<Element>> Declared In Collection, Sequence func dropLast() Returns a subsequence containing all but the last element of the sequence. The sequence must be finite. If the sequence has no elements, the result is an empty subsequence. let numbers = [1, 2, 3, 4, 5] print(numbers.dropLast()) // Prints "[1, 2, 3, 4]" If the sequence has no elements, the result is an empty subsequence. let empty: [Int] = [] print(empty.dropLast()) // Prints "[]" Returns: A subsequence leaving off the last element of the sequence. Complexity: O(n), where n is the length of the sequence. Declaration func dropLast() -> Slice<Set<Element>> Declared In Collection, Sequence func dropLast(_:) 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 "[]" n: The number of elements to drop off the end of the collection. n must be greater than or equal to zero. Returns: A subsequence that leaves off the specified number of elements at the end. Complexity: O(n), where n is the length of the collection. Declaration func dropLast(_ n: Int) -> Slice<Set<Element>> Declared In Collection, Sequence func elementsEqual(_:) Returns a Boolean value indicating whether this sequence and another sequence contain the same elements in the same order. At least one of the sequences must be finite. This example tests whether one countable range shares the same elements as another countable range and an array. let a = 1...3 let b = 1...10 print(a.elementsEqual(b)) // Prints "false" print(a.elementsEqual([1, 2, 3])) // Prints "true" other: A sequence to compare to this sequence. Returns: true if this sequence and other contain the same elements in the same order. See Also: elementsEqual(_:by:) Declaration func elementsEqual<OtherSequence where OtherSequence : Sequence, OtherSequence.Iterator.Element == Iterator.Element>(_ other: OtherSequence) -> Bool Declared In Collection, Sequence func elementsEqual(_:by:) Returns a Boolean value indicating whether this sequence and another sequence contain equivalent elements, 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: areEquivalent(a, a) is always true. (Reflexivity) areEquivalent(a, b) implies areEquivalent(b, a). (Symmetry) If areEquivalent(a, b) and areEquivalent(b, c) are both true, then areEquivalent(a, c) is also true. (Transitivity) Parameters: other: A sequence to compare to this sequence. areEquivalent: A predicate that returns true if its two arguments are equivalent; otherwise, false. Returns: true if this sequence and other contain equivalent items, using areEquivalent as the equivalence test; otherwise, false. See Also: elementsEqual(_:) Declaration func elementsEqual<OtherSequence where OtherSequence : Sequence, OtherSequence.Iterator.Element == Iterator.Element>(_ other: OtherSequence, by areEquivalent: (Element, Element) throws -> Bool) rethrows -> Bool Declared In Collection, Sequence func enumerated() Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero, and x represents an element of the sequence. 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".characters.enumerated() { print("\(n): '\(c)'") } // Prints "0: 'S'" // Prints "1: 'w'" // Prints "2: 'i'" // Prints "3: 'f'" // Prints "4: 't'" When enumerating a collection, the integer part of each pair is a counter for the enumeration, not necessarily the index of the paired value. These counters can only be used as indices 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 of indices of names with five or fewer letters. let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"] var shorterIndices: [SetIndex<String>] = [] for (i, name) in zip(names.indices, names) { if name.characters.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" Returns: A sequence of pairs enumerating the sequence. Declaration func enumerated() -> EnumeratedSequence<Set<Element>> Declared In Collection, Sequence func filter(_:) 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.characters.count < 5 } print(shortNames) // Prints "["Kim", "Karl"]" shouldInclude: 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. Returns: An array of the elements that includeElement allowed. Declaration func filter(_ isIncluded: (Element) throws -> Bool) rethrows -> [Element] Declared In Collection, Sequence func first(where:) Returns the first element of the sequence that satisfies the given predicate or nil if no such element is found. 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. Returns: The first match or nil if there was no match. Declaration func first(where predicate: (Element) throws -> Bool) rethrows -> Element? Declared In Collection, Sequence func flatMap<ElementOfResult>(_: (Element) throws -> ElementOfResult?) 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 nonoptional values when your transformation produces an optional value. In this example, note the difference in the result of using map and flatMap with a transformation that returns an optional Int value. let possibleNumbers = ["1", "2", "three", "///4///", "5"] let mapped: [Int?] = numbers.map { str in Int(str) } // [1, 2, nil, nil, 5] let flatMapped: [Int] = numbers.flatMap { str in Int(str) } // [1, 2, 5] transform: A closure that accepts an element of this sequence as its argument and returns an optional value. Returns: An array of the non-nil results of calling transform with each element of the sequence. Complexity: O(m + n), where m is the length of this sequence and n is the length of the result. Declaration func flatMap<ElementOfResult>(_ transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] Declared In Collection, Sequence func flatMap<SegmentOfResult : Sequence>(_: (Element) throws -> SegmentOfResult) 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(count: $0, repeatedValue: $0) } // [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]] let flatMapped = numbers.flatMap { Array(count: $0, repeatedValue: $0) } // [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] In fact, s.flatMap(transform) is equivalent to Array(s.map(transform).joined()). transform: A closure that accepts an element of this sequence as its argument and returns a sequence or collection. Returns: The resulting flattened array. Complexity: O(m + n), where m is the length of this sequence and n is the length of the result. See Also: joined(), map(_:) Declaration func flatMap<SegmentOfResult : Sequence>(_ transform: (Element) throws -> SegmentOfResult) rethrows -> [SegmentOfResult.Iterator.Element] Declared In Collection, Sequence func forEach(_:) 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: You cannot use a break or continue statement to exit the current call of the body closure or skip subsequent calls. 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. body: A closure that takes an element of the sequence as a parameter. Declaration func forEach(_ body: (Element) throws -> Swift.Void) rethrows Declared In Collection, Sequence func formIndex(_:offsetBy:) Offsets the given index by the specified distance. The value passed as n must not offset i beyond the endIndex or before the startIndex of this collection. Parameters: i: A valid index of the collection. n: The distance to offset i. n must not be negative unless the collection conforms to the BidirectionalCollection protocol. See Also: index(_:offsetBy:), formIndex(_:offsetBy:limitedBy:) Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the absolute value of n. Declaration func formIndex(_ i: inout SetIndex<Element>, offsetBy n: SetIndex<Element>Distance) Declared In Collection, Indexable func formIndex(_:offsetBy:limitedBy:) Offsets the given index by the specified distance, or so that it equals the given limiting index. The value passed as n must not offset i beyond the endIndex or before the startIndex of this collection, unless the index passed as limit prevents offsetting beyond those bounds. Parameters: i: A valid index of the collection. n: The distance to offset i. n must not be negative unless the collection conforms to the BidirectionalCollection protocol. Returns: true if i has been offset by exactly n steps without going beyond limit; otherwise, false. When the return value is false, the value of i is equal to limit. See Also: index(_:offsetBy:), formIndex(_:offsetBy:limitedBy:) Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the absolute value of n. Declaration func formIndex(_ i: inout SetIndex<Element>, offsetBy n: SetIndex<Element>Distance, limitedBy limit: SetIndex<Element>) -> Bool Declared In Collection, Indexable func formIndex(after:) Replaces the given index with its successor. i: A valid index of the collection. i must be less than endIndex. Declaration func formIndex(after i: inout SetIndex<Element>) Declared In Collection, Indexable mutating func formIntersection(_:) 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"]" other: A sequence of elements. other must be finite. Declaration mutating func formIntersection<S : Sequence where S.Iterator.Element == Element>(_ other: S) mutating func formSymmetricDifference(_: Set<Element>) Removes the elements of the set that are also in the given sequence and adds the members of the sequence that are not already in the set. 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"]" other: Another set. Declaration mutating func formSymmetricDifference(_ other: Set<Element>) mutating func formSymmetricDifference<S : Sequence where S.Iterator.Element == Element>(_: S) 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 "Alicia", "Chris", and "Diana" 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"]" other: A sequence of elements. other must be finite. Declaration mutating func formSymmetricDifference<S : Sequence where S.Iterator.Element == Element>(_ other: S) mutating func formUnion(_:) 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"]" other: A sequence of elements. other must be finite. Declaration mutating func formUnion<S : Sequence where S.Iterator.Element == Element>(_ other: S) func index(_:offsetBy:) 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 n must not offset i beyond the endIndex or before the startIndex of this collection. Parameters: i: A valid index of the collection. n: The distance to offset i. n must not be negative unless the collection conforms to the BidirectionalCollection protocol. Returns: An index offset by n from the index i. If n is positive, this is the same value as the result of n calls to index(after:). If n is negative, this is the same value as the result of -n calls to index(before:). See Also: index(_:offsetBy:limitedBy:), formIndex(_:offsetBy:) Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the absolute value of n. Declaration func index(_ i: SetIndex<Element>, offsetBy n: SetIndex<Element>Distance) -> SetIndex<Element> Declared In Collection, Indexable func index(_:offsetBy:limitedBy:) 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 n must not offset i beyond the endIndex or before the startIndex of this collection, unless the index passed as limit prevents offsetting beyond those bounds. Parameters: i: A valid index of the collection. n: The distance to offset i. n must not be negative unless the collection conforms to the BidirectionalCollection protocol. limit: A valid index of the collection to use as a limit. If n > 0, a limit that is less than i has no effect. Likewise, if n < 0, a limit that is greater than i has no effect. Returns: An index offset by n from the index i, unless that index would be beyond limit in the direction of movement. In that case, the method returns nil. See Also: index(_:offsetBy:), formIndex(_:offsetBy:limitedBy:) Complexity: O(1) if the collection conforms to RandomAccessCollection; otherwise, O(n), where n is the absolute value of n. Declaration func index(_ i: SetIndex<Element>, offsetBy n: SetIndex<Element>Distance, limitedBy limit: SetIndex<Element>) -> SetIndex<Element>? Declared In Collection, Indexable func index(after:) Returns the position immediately after the given index. i: A valid index of the collection. i must be less than endIndex. Returns: The index value immediately after i. Declaration func index(after i: SetIndex<Element>) -> SetIndex<Element> func index(of:) Returns the index of the given element in the set, or nil if the element is not a member of the set. member: An element to search for in the set. Returns: The index of member if it exists in the set; otherwise, nil. Declaration func index(of member: Element) -> SetIndex<Element>? Declared In Set, Collection func index(where:) 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.index(where: { $0.hasPrefix("A") }) { print("\(students[i]) starts with 'A'!") } // Prints "Abena starts with 'A'!" predicate: A closure that takes an element as its argument and returns a Boolean value that indicates whether the passed element represents a match. Returns: The index of the first element for which predicate returns true. If no elements in the collection satisfy the given predicate, returns nil. See Also: index(of:) Declaration func index(where predicate: (Element) throws -> Bool) rethrows -> SetIndex<Element>? Declared In Collection mutating func insert(_: Element) 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]" newMember: An element to insert into the set. Returns: (true, newMember) if newMember was not contained in the set. If an element equal to newMember was already contained in the set, the method returns (false, oldMember), where oldMember is the element that was equal to newMember. In some cases, oldMember may be distinguishable from newMember by identity comparison or some other means. Declaration mutating func insert(_ newMember: Element) -> (inserted: Bool, memberAfterInsert: Element) mutating func insert<ConcreteElement : Hashable>(_: ConcreteElement) Declaration mutating func insert<ConcreteElement : Hashable>(_ newMember: ConcreteElement) -> (inserted: Bool, memberAfterInsert: ConcreteElement) func intersection(_: Set<Element>) 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 either one or the other, but not both, 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"]" other: Another set. Returns: A new set. Declaration func intersection(_ other: Set<Element>) -> Set<Element> func intersection<S : Sequence where S.Iterator.Element == Element>(_: S) 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 either one or the other, but not both, 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"]" other: A sequence of elements. other must be finite. Returns: A new set. Declaration func intersection<S : Sequence where S.Iterator.Element == Element>(_ other: S) -> Set<Element> func isDisjoint(with: Set<Element>) 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" other: Another set. Returns: true if the set has no elements in common with other; otherwise, false. Declaration func isDisjoint(with other: Set<Element>) -> Bool func isDisjoint(with:) 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" other: A set of the same type as the current set. Returns: true if the set has no elements in common with other; otherwise, false. Declaration func isDisjoint(with other: Set<Element>) -> Bool Declared In SetAlgebra func isDisjoint<S : Sequence where S.Iterator.Element == Element>(with: S) 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" other: A sequence of elements. other must be finite. Returns: true if the set has no elements in common with other; otherwise, false. Declaration func isDisjoint<S : Sequence where S.Iterator.Element == Element>(with other: S) -> Bool func isStrictSubset(of: Set<Element>) 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" possibleStrictSuperset: Another set. Returns: true if the set is a strict subset of possibleStrictSuperset; otherwise, false. Declaration func isStrictSubset(of other: Set<Element>) -> Bool func isStrictSubset(of:) 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" other: A set of the same type as the current set. Returns: true if the set is a strict subset of other; otherwise, false. Declaration func isStrictSubset(of other: Set<Element>) -> Bool Declared In SetAlgebra func isStrictSubset<S : Sequence where S.Iterator.Element == Element>(of: S) 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" possibleStrictSuperset: A sequence of elements. possibleStrictSuperset must be finite. Returns: true is the set is strict subset of possibleStrictSuperset; otherwise, false. Declaration func isStrictSubset<S : Sequence where S.Iterator.Element == Element>(of possibleStrictSuperset: S) -> Bool func isStrictSuperset(of: Set<Element>) 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" possibleStrictSubset: Another set. Returns: true if the set is a strict superset of possibleStrictSubset; otherwise, false. Declaration func isStrictSuperset(of other: Set<Element>) -> Bool func isStrictSuperset(of:) 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" other: A set of the same type as the current set. Returns: true if the set is a strict superset of other; otherwise, false. Declaration func isStrictSuperset(of other: Set<Element>) -> Bool Declared In SetAlgebra func isStrictSuperset<S : Sequence where S.Iterator.Element == Element>(of: S) 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" possibleStrictSubset: A sequence of elements. possibleStrictSubset must be finite. Returns: true if the set is a strict superset of possibleStrictSubset; otherwise, false. Declaration func isStrictSuperset<S : Sequence where S.Iterator.Element == Element>(of possibleStrictSubset: S) -> Bool func isSubset(of: Set<Element>) 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" other: A sequence of elements. possibleSuperset must be finite. Returns: true if the set is a subset of possibleSuperset; otherwise, false. Declaration func isSubset(of other: Set<Element>) -> Bool func isSubset(of:) 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" other: A set of the same type as the current set. Returns: true if the set is a subset of other; otherwise, false. Declaration func isSubset(of other: Set<Element>) -> Bool Declared In SetAlgebra func isSubset<S : Sequence where S.Iterator.Element == Element>(of: S) 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" possibleSuperset: A sequence of elements. possibleSuperset must be finite. Returns: true if the set is a subset of possibleSuperset; otherwise, false. Declaration func isSubset<S : Sequence where S.Iterator.Element == Element>(of possibleSuperset: S) -> Bool func isSuperset(of: Set<Element>) 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" possibleSubset: Another set. Returns: true if the set is a superset of possibleSubset; otherwise, false. Declaration func isSuperset(of other: Set<Element>) -> Bool func isSuperset(of:) 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" other: A set of the same type as the current set. Returns: true if the set is a superset of other; otherwise, false. Declaration func isSuperset(of other: Set<Element>) -> Bool Declared In SetAlgebra func isSuperset<S : Sequence where S.Iterator.Element == Element>(of: S) 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" possibleSubset: A sequence of elements. possibleSubset must be finite. Returns: true if the set is a superset of possibleSubset; otherwise, false. Declaration func isSuperset<S : Sequence where S.Iterator.Element == Element>(of possibleSubset: S) -> Bool func lexicographicallyPrecedes(_:by:) 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: areInIncreasingOrder(a, a) is always false. (Irreflexivity) If areInIncreasingOrder(a, b) and areInIncreasingOrder(b, c) are both true, then areInIncreasingOrder(a, c) is also true. (Transitive comparability) Two elements are incomparable if neither is ordered before the other according to the predicate. If a and b are incomparable, and b and c are incomparable, then a and c are also incomparable. (Transitive incomparability) Parameters: other: A sequence to compare to this sequence. areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false. Returns: true if this sequence precedes other in a dictionary ordering as ordered by areInIncreasingOrder; otherwise, false. 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. See Also: lexicographicallyPrecedes(_:) Declaration func lexicographicallyPrecedes<OtherSequence where OtherSequence : Sequence, OtherSequence.Iterator.Element == Iterator.Element>(_ other: OtherSequence, by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> Bool Declared In Collection, Sequence func makeIterator() Returns an iterator over the members of the set. Declaration func makeIterator() -> SetIterator<Element> func map(_:) 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.lowercaseString } // 'lowercaseNames' == ["vivien", "marlon", "kim", "karl"] let letterCounts = cast.map { $0.characters.count } // 'letterCounts' == [6, 6, 3, 4] 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. Returns: An array containing the transformed elements of this sequence. Declaration func map<T>(_ transform: (Element) throws -> T) rethrows -> [T] Declared In Collection, Sequence @warn_unqualified_access func max(by:) 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: areInIncreasingOrder(a, a) is always false. (Irreflexivity) If areInIncreasingOrder(a, b) and areInIncreasingOrder(b, c) are both true, then areInIncreasingOrder(a, c) is also true. (Transitive comparability) Two elements are incomparable if neither is ordered before the other according to the predicate. If a and b are incomparable, and b and c are incomparable, then a and c are also incomparable. (Transitive incomparability) 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))" areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false. Returns: The sequence's maximum element if the sequence is not empty; otherwise, nil. See Also: max() Declaration @warn_unqualified_access func max(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> Element? Declared In Collection, Sequence @warn_unqualified_access func min(by:) 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: areInIncreasingOrder(a, a) is always false. (Irreflexivity) If areInIncreasingOrder(a, b) and areInIncreasingOrder(b, c) are both true, then areInIncreasingOrder(a, c) is also true. (Transitive comparability) Two elements are incomparable if neither is ordered before the other according to the predicate. If a and b are incomparable, and b and c are incomparable, then a and c are also incomparable. (Transitive incomparability) 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))" areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false. Returns: The sequence's minimum element, according to areInIncreasingOrder. If the sequence has no elements, returns nil. See Also: min() Declaration @warn_unqualified_access func min(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> Element? Declared In Collection, Sequence mutating func popFirst() 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. Returns: A member of the set. If the set is empty, returns nil. Declaration mutating func popFirst() -> Element? func prefix(_:) 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]" maxLength: The maximum number of elements to return. maxLength must be greater than or equal to zero. Returns: A subsequence starting at the beginning of this collection with at most maxLength elements. Declaration func prefix(_ maxLength: Int) -> Slice<Set<Element>> Declared In Collection, Sequence func prefix(through:) 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.index(of: 40) { print(numbers.prefix(through: i)) } // Prints "[10, 20, 30, 40]" 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. Returns: A subsequence up to, and including, the end position. Complexity: O(1) See Also: prefix(upTo:) Declaration func prefix(through position: SetIndex<Element>) -> Slice<Set<Element>> Declared In Collection func prefix(upTo:) 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.index(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 "[]" end: The "past the end" index of the resulting subsequence. end must be a valid index of the collection. Returns: A subsequence up to, but not including, the end position. Complexity: O(1) See Also: prefix(through:) Declaration func prefix(upTo end: SetIndex<Element>) -> Slice<Set<Element>> Declared In Collection func reduce(_:_:) Returns the result of calling the given combining closure with each element of this sequence and an accumulating value. 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 addTwo: (Int, Int) -> Int = { x, y in x + y } let numberSum = numbers.reduce(0, addTwo) // 'numberSum' == 10 When numbers.reduce(_:_:) is called, the following steps occur: The nextPartialResult closure is called with the initial result and the first element of numbers, returning the sum: 1. The closure is called again repeatedly with the previous call's return value and each element of the sequence. When the sequence is exhausted, the last value returned from the closure is returned to the caller. Parameters: initialResult: the initial accumulating value. nextPartialResult: A closure that combines an accumulating value and an element of the sequence into a new accumulating value, to be used in the next call of the nextPartialResult closure or returned to the caller. Returns: The final accumulated value. Declaration func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result Declared In Collection, Sequence mutating func remove(_: Element) 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." member: The element to remove from the set. Returns: The value of the member parameter if it was a member of the set; otherwise, nil. Declaration mutating func remove(_ member: Element) -> Element? mutating func remove<ConcreteElement : Hashable>(_: ConcreteElement) Declaration mutating func remove<ConcreteElement : Hashable>(_ member: ConcreteElement) -> ConcreteElement? mutating func remove(at:) Removes the element at the given index of the set. 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. Returns: The element that was removed from the set. Declaration mutating func remove(at position: SetIndex<Element>) -> Element mutating func removeAll(keepingCapacity:) Removes all members from the set. keepingCapacity: If true, the set's storage capacity is preserved; if false, the underlying storage is released. The default is false. Declaration mutating func removeAll(keepingCapacity keepCapacity: Bool = default) mutating func removeFirst() 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. Returns: A member of the set. Declaration mutating func removeFirst() -> Element func reversed() 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. Returns: An array containing the elements of this sequence in reverse order. Declaration func reversed() -> [Element] Declared In Collection, Sequence func sorted(by:) 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 passed should be ordered before the second. The elements of the resulting array are ordered according to the given predicate. 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: areInIncreasingOrder(a, a) is always false. (Irreflexivity) If areInIncreasingOrder(a, b) and areInIncreasingOrder(b, c) are both true, then areInIncreasingOrder(a, c) is also true. (Transitive comparability) Two elements are incomparable if neither is ordered before the other according to the predicate. If a and b are incomparable, and b and c are incomparable, then a and c are also incomparable. (Transitive incomparability) The sorting algorithm is not stable. A nonstable sort may change the relative order of elements for which areInIncreasingOrder does not establish an order. 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"]" areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false. Returns: A sorted array of the sequence's elements. See Also: sorted() Declaration func sorted(by areInIncreasingOrder: (Element, Element) -> Bool) -> [Element] Declared In Collection, Sequence func split(_:maxSplits:omittingEmptySubsequences:) Returns the longest possible subsequences of the collection, in order, around elements equal to the given element. The resulting array consists of at most maxSplits + 1 subsequences. Elements that are used to split the collection are not returned as part of any subsequence. The following examples show the effects of the maxSplits and omittingEmptySubsequences parameters when splitting a string at each space character (" "). 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.characters.split(separator: " ") .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.characters.split(separator: " ", maxSplits: 1) .map(String.init)) // 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.characters.split(separator: " ", omittingEmptySubsequences: false) .map(String.init)) // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" Parameters: separator: The element that should be split upon. maxSplits: The maximum number of times to split the collection, or one less than the number of subsequences to return. If maxSplits + 1 subsequences are returned, the last one is a suffix of the original collection containing the remaining elements. maxSplits must be greater than or equal to zero. The default value is Int.max. omittingEmptySubsequences: If false, an empty subsequence is returned in the result for each consecutive pair of separator elements in the collection and for each instance of separator at the start or end of the collection. If true, only nonempty subsequences are returned. The default value is true. Returns: An array of subsequences, split from this collection's elements. Declaration func split(separator: Element, maxSplits: Int = default, omittingEmptySubsequences: Bool = default) -> [Slice<Set<Element>>] Declared In Collection, Sequence func split(_:omittingEmptySubsequences:whereSeparator:) 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.characters.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.characters.split( maxSplits: 1, whereSeparator: { $0 == " " } ).map(String.init)) // 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.characters.split(omittingEmptySubsequences: false, whereSeparator: { $0 == " " }) .map(String.init)) // Prints "["BLANCHE:", "", "", "I", "don\'t", "want", "realism.", "I", "want", "magic!"]" Parameters: maxSplits: The maximum number of times to split the collection, or one less than the number of subsequences to return. If maxSplits + 1 subsequences are returned, the last one is a suffix of the original collection containing the remaining elements. maxSplits must be greater than or equal to zero. The default value is Int.max. omittingEmptySubsequences: If false, an empty subsequence is returned in the result for each pair of consecutive elements satisfying the isSeparator predicate and for each element at the start or end of the collection satisfying the isSeparator predicate. The default value is true. isSeparator: A closure that takes an element as an argument and returns a Boolean value indicating whether the collection should be split at that element. Returns: An array of subsequences, split from this collection's elements. Declaration func split(maxSplits: Int = default, omittingEmptySubsequences: Bool = default, whereSeparator isSeparator: (Element) throws -> Bool) rethrows -> [Slice<Set<Element>>] Declared In Collection, Sequence func starts(with:) Returns a Boolean value indicating whether the initial elements of the sequence are the same as the elements in another sequence. This example tests whether one countable range begins with the elements of another countable range. let a = 1...3 let b = 1...10 print(b.starts(with: a)) // Prints "true" Passing an sequence with no elements or an empty collection as possiblePrefix always results in true. print(b.starts(with: [])) // Prints "true" possiblePrefix: A sequence to compare to this sequence. Returns: true if the initial elements of the sequence are the same as the elements of possiblePrefix; otherwise, false. If possiblePrefix has no elements, the return value is true. See Also: starts(with:by:) Declaration func starts<PossiblePrefix where PossiblePrefix : Sequence, PossiblePrefix.Iterator.Element == Iterator.Element>(with possiblePrefix: PossiblePrefix) -> Bool Declared In Collection, Sequence func starts(with:by:) 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: areEquivalent(a, a) is always true. (Reflexivity) areEquivalent(a, b) implies areEquivalent(b, a). (Symmetry) If areEquivalent(a, b) and areEquivalent(b, c) are both true, then areEquivalent(a, c) is also true. (Transitivity) Parameters: possiblePrefix: A sequence to compare to this sequence. areEquivalent: A predicate that returns true if its two arguments are equivalent; otherwise, false. Returns: true if the initial elements of the sequence are equivalent to the elements of possiblePrefix; otherwise, false. If possiblePrefix has no elements, the return value is true. See Also: starts(with:) Declaration func starts<PossiblePrefix where PossiblePrefix : Sequence, PossiblePrefix.Iterator.Element == Iterator.Element>(with possiblePrefix: PossiblePrefix, by areEquivalent: (Element, Element) throws -> Bool) rethrows -> Bool Declared In Collection, Sequence mutating func subtract(_: Set<Element>) 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"]" other: Another set. Declaration mutating func subtract(_ other: Set<Element>) mutating func subtract(_:) 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"]" other: A set of the same type as the current set. Declaration mutating func subtract(_ other: Set<Element>) Declared In SetAlgebra mutating func subtract<S : Sequence where S.Iterator.Element == Element>(_: S) 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"]" other: A sequence of elements. other must be finite. Declaration mutating func subtract<S : Sequence where S.Iterator.Element == Element>(_ other: S) func subtracting(_: Set<Element>) 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"]" other: Another set. Returns: A new set. Declaration func subtracting(_ other: Set<Element>) -> Set<Element> func subtracting(_:) 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"]" other: A set of the same type as the current set. Returns: A new set. Declaration func subtracting(_ other: Set<Element>) -> Set<Element> Declared In SetAlgebra func subtracting<S : Sequence where S.Iterator.Element == Element>(_: S) 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"]" other: A sequence of elements. other must be finite. Returns: A new set. Declaration func subtracting<S : Sequence where S.Iterator.Element == Element>(_ other: S) -> Set<Element> func suffix(_:) 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]" maxLength: The maximum number of elements to return. The value of maxLength must be greater than or equal to zero. Returns: A subsequence terminating at the end of the collection with at most maxLength elements. Complexity: O(n), where n is the length of the collection. Declaration func suffix(_ maxLength: Int) -> Slice<Set<Element>> Declared In Collection, Sequence func suffix(from:) 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.index(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 "[]" start: The index at which to start the resulting subsequence. start must be a valid index of the collection. Returns: A subsequence starting at the start position. Complexity: O(1) Declaration func suffix(from start: SetIndex<Element>) -> Slice<Set<Element>> Declared In Collection func symmetricDifference(_:) 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"]" other: A sequence of elements. other must be finite. Returns: A new set. Declaration func symmetricDifference<S : Sequence where S.Iterator.Element == Element>(_ other: S) -> Set<Element> func union(_:) 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]" other: A sequence of elements. other must be finite. Returns: A new set with the unique elements of this set and other. Declaration func union<S : Sequence where S.Iterator.Element == Element>(_ other: S) -> Set<Element> mutating func update(with: Element) 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)" newMember: An element to insert into the set. Returns: An element equal to newMember if the set already contained such a member; otherwise, nil. In some cases, the returned element may be distinguishable from newMember by identity comparison or some other means. Declaration mutating func update(with newMember: Element) -> Element? mutating func update<ConcreteElement : Hashable>(with: ConcreteElement) Declaration mutating func update<ConcreteElement : Hashable>(with newMember: ConcreteElement) -> ConcreteElement? Conditionally Inherited Items The initializers, methods, and properties listed below may be available on this type under certain conditions (such as methods that are available on Array when its elements are Equatable) or may not ever be available if that determination is beyond SwiftDoc.org's capabilities. Please open an issue on GitHub if you see something out of place! Where Indices == DefaultIndices var indices: DefaultIndices<Set<Element>> The indices that are valid for subscripting the collection, in ascending order. A collection's indices property can hold a strong reference to the collection itself, causing the collection to be non-uniquely referenced. If you mutate the collection while iterating over its indices, a strong reference can cause an unexpected copy of the collection. To avoid the unexpected copy, use the index(after:) method starting with startIndex to produce indices instead. var c = MyFancyCollection([10, 20, 30, 40, 50]) var i = c.startIndex while i != c.endIndex { c[i] /= 5 i = c.index(after: i) } // c == MyFancyCollection([2, 4, 6, 8, 10]) Declaration var indices: DefaultIndices<Set<Element>> { get } Declared In Collection Where Iterator.Element : Collection func joined() Returns the elements of this collection of collections, concatenated. In this example, an array of three ranges is flattened so that the elements of each range can be iterated in turn. let ranges = [0..<3, 8..<10, 15..<17] // A for-in loop over 'ranges' accesses each range: for range in ranges { print(range) } // Prints "0..<3" // Prints "8..<10" // Prints "15..<17" // Use 'joined()' to access each element of each range: for index in ranges.joined() { print(index, terminator: " ") } // Prints: "0 1 2 8 9 15 16" Returns: A flattened view of the elements of this collection of collections. See Also: flatMap(_:), joined(separator:) Declaration func joined() -> FlattenCollection<Set<Element>> Declared In Collection Where Iterator.Element : Comparable func lexicographicallyPrecedes(_:) Returns a Boolean value indicating whether the sequence precedes another sequence in a lexicographical (dictionary) ordering, using the less-than operator (<) to compare elements. This example uses the lexicographicallyPrecedes method to test which array of integers comes first in a lexicographical ordering. let a = [1, 2, 2, 2] let b = [1, 2, 3, 4] print(a.lexicographicallyPrecedes(b)) // Prints "true" print(b.lexicographicallyPrecedes(b)) // Prints "false" other: A sequence to compare to this sequence. Returns: true if this sequence precedes other in a dictionary ordering; otherwise, false. 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. See Also: lexicographicallyPrecedes(_:by:) Declaration func lexicographicallyPrecedes<OtherSequence where OtherSequence : Sequence, OtherSequence.Iterator.Element == Iterator.Element>(_ other: OtherSequence) -> Bool Declared In Collection, Sequence @warn_unqualified_access func max() Returns the maximum element in the sequence. This example finds the smallest value in an array of height measurements. let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9] let greatestHeight = heights.max() print(greatestHeight) // Prints "Optional(67.5)" Returns: The sequence's maximum element. If the sequence has no elements, returns nil. See Also: max(by:) Declaration @warn_unqualified_access func max() -> Element? Declared In Collection, Sequence @warn_unqualified_access func min() Returns the minimum element in the sequence. This example finds the smallest value in an array of height measurements. let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9] let lowestHeight = heights.min() print(lowestHeight) // Prints "Optional(58.5)" Returns: The sequence's minimum element. If the sequence has no elements, returns nil. See Also: min(by:) Declaration @warn_unqualified_access func min() -> Element? Declared In Collection, Sequence func sorted() Returns the elements of the sequence, sorted. You can sort any sequence of elements that conform to the Comparable protocol by calling this method. Elements are sorted in ascending order. The sorting algorithm is not stable. A nonstable sort may change the relative order of elements that compare equal. Here's an example of sorting a list of students' names. Strings in Swift conform to the Comparable protocol, so the names are sorted in ascending order according to the less-than operator (<). let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"] let sortedStudents = students.sorted() print(sortedStudents) // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]" To sort the elements of your sequence in descending order, pass the greater-than operator (>) to the sorted(by:) method. let descendingStudents = students.sorted(by: >) print(descendingStudents) // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]" Returns: A sorted array of the sequence's elements. See Also: sorted(by:) Declaration func sorted() -> [Element] Declared In Collection, Sequence Where Iterator.Element : Sequence func joined() Returns the elements of this sequence of sequences, concatenated. In this example, an array of three ranges is flattened so that the elements of each range can be iterated in turn. let ranges = [0..<3, 8..<10, 15..<17] // A for-in loop over 'ranges' accesses each range: for range in ranges { print(range) } // Prints "0..<3" // Prints "8..<10" // Prints "15..<17" // Use 'joined()' to access each element of each range: for index in ranges.joined() { print(index, terminator: " ") } // Prints: "0 1 2 8 9 15 16" Returns: A flattened view of the elements of this sequence of sequences. See Also: flatMap(_:), joined(separator:) Declaration func joined() -> FlattenSequence<Set<Element>> Declared In Collection, Sequence func joined(_:) Returns the concatenated elements of this sequence of sequences, inserting the given separator between each element. This example shows how an array of [Int] instances can be joined, using another [Int] instance as the separator: let nestedNumbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] let joined = nestedNumbers.joined(separator: [-1, -2]) print(Array(joined)) // Prints "[1, 2, 3, -1, -2, 4, 5, 6, -1, -2, 7, 8, 9]" separator: A sequence to insert between each of this sequence's elements. Returns: The joined sequence of elements. See Also: joined() Declaration func joined<Separator : Sequence where Separator.Iterator.Element == Iterator.Element.Iterator.Element>(separator: Separator) -> JoinedSequence<Set<Element>> Declared In Collection, Sequence Where Iterator.Element == String func joined(_:) Returns a new string by concatenating the elements of the sequence, adding the given separator between each element. The following example shows how an array of strings can be joined to a single, comma-separated string: let cast = ["Vivien", "Marlon", "Kim", "Karl"] let list = cast.joined(separator: ", ") print(list) // Prints "Vivien, Marlon, Kim, Karl" separator: A string to insert between each of the elements in this sequence. The default separator is an empty string. Returns: A single, concatenated string. Declaration func joined(separator: String = default) -> String Declared In Collection, Sequence