Another set operation we can use is .union()
. This operation creates a set by combining the values of two sets together.
The syntax for creating a set using .union()
is:
var NewSet = SetA.union(SetB)
Consider the following sets book1
and book2
that contain the characters of different fairy tales:
var book1: Set = ["Pig 1", "Pig 2", "Pig 3", "Wolf"] var book2: Set = ["Little Red Riding Hood", "Grandma", "Wolf"]
We can use .union()
to combine all the characters into one set called fairyTales
:
var fairyTales = book1.union(book2)
Imagine finding a third book, book3
:
var book3: Set = ["Jack", "Blunderbore", "Beanstock"]
With set operations, we can combine multiple sets like this:
var fairyTales = book1.union(book2).union(book3)
Using multiple methods in the same line of code is known as method chaining.
When we print fairyTales
, we will get something similar to the following output:
["Blunderbore", "Pig 1", "Pig 2", "Little Red Riding Hood", "Pig 3", "Grandma", "Wolf", "Jack", "Beanstock"]
The element "Wolf"
appeared in both book1
and book2
; however, the element only appears once in fairyTales
because sets only contain unique elements.
Instructions
In Alphabet.swift, create a set called alphabet
that uses .union()
to combine the values of the sets consonants
and vowels
.
Use print()
to output alphabet
.