Swift .union()

hcz's avatar
Published Oct 24, 2022
Contribute to Docs

The .union() method returns a new set containing all elements of one set combined with the elements of a given set.

  • Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.
    • Includes 7 Courses
    • With Certificate
    • Beginner Friendly.
      13 hours
  • A powerful programming language developed by Apple for iOS, macOS, and more.
    • Beginner Friendly.
      12 hours

Syntax

firstSet.union(secondSet)

Sets firstSet and secondSet must have countable number of members.

Example

let friends: Set = ["Pam", "Jim", "Andy", "Darryl"]
let colleagues = ["Dwight", "Michael", "Ed"]
let friendsAndColleagues = friends.union(colleagues)
print(friendsAndColleagues)
let luckyNumbers: Set = [12, 13]
let luckySequence = (4...8)
let goodNumbers = luckyNumbers.union(luckySequence)
print(goodNumbers)

This will output:

["Darryl", "Pam", "Jim", "Ed", "Andy", "Michael", "Dwight"]
[12, 4, 5, 6, 7, 8, 13]

Note: A set is an unordered data structure, so output elements may be ordered differently.

All contributors

Contribute to Docs

Learn Swift on Codecademy

  • Learn how to build iOS applications with Swift and SwiftUI and publish them to Apples' App Store.
    • Includes 7 Courses
    • With Certificate
    • Beginner Friendly.
      13 hours
  • A powerful programming language developed by Apple for iOS, macOS, and more.
    • Beginner Friendly.
      12 hours