Related Tags

swift
communitycreator

# How to form a union between a set and an array in Swift

Theodore Kelechukwu Onyejiaku

### Overview

A set is a sequence with unique elements. A union is a set that contains elements present in two or more sets. An array is a sequence that contains elements that are not necessarily unique. We use the formUnion() method to form a union between a set and an array.

### Syntax

nset.formUnion(array)
The syntax for the union between a set and an array sequence

### Parameter

array: This is the array whose union we want to form with the set set.

### Return value

It returns a set, set, as a union of itself and the array array.

### Example

// create some sets
var names: Set = ["Alicia", "John", "Diana"]
var numbers1: Set = [1, 2, 3, 4, 5, 7, 8, 9, 10]
var numbers2 : Set = [10, 20,1000]

// create some arrays
let last_names = ["Diana", "Doe", "Daniel"]
let prime_numbers = [2, 3, 5, 7, 11]
let even_numbers = [2, 4, 6, 8, 10]

// get the unions
names.formUnion(last_names)
numbers1.formUnion(prime_numbers)
numbers2.formUnion(even_numbers)

// print unions
print(names)
print(numbers1)
print(numbers2)
Form a union between a set and an array

### Explanation

• Line 2–4: We create some sets and initialize them with some values.
• Line 7–9: We also create some arrays.
• Line 11–13: We use the formUnion() method to form the unions.
• Line 17–19: We print the unions created to the console.

RELATED TAGS

swift
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time