union(_:)
Returns a new set with the elements of both this set and the given sequence.
Declaration
func union<S>(_ other: S) -> Set<Element> where Element == S.Element, S : SequenceParameters
- other:
A sequence of elements.
othermust be finite.
Return Value
A new set with the unique elements of this set and other.
Discussion
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]"