Contents

About Swift Syntax 5 (Frequently Used Functions in Set Types)

   Jan 19, 2024     2 min read

About “Swift Syntax 5”

I had the opportunity to study iOS this week, and I’ve been studying grammar, so I thought I’d write a post to summarize it.

In this post, I’ll introduce various functions of the Set type that are often used.

First of all, what is the Set type?

What is the Set type?

A collection that stores unique values of the same type.

No order is guaranteed, and each element appears only once.

Creation and initialization

How to create and initialize a Set.

Example
var color: Set<String> = ["Red", "Green", "Blue"]

insert

Adds an element to the set. Duplicate values will not be added.

Example: #####

colors.insert("Yellow") // colors: ["Red", "Green", "Blue", "Yellow"]

remove

Remove a specific element.

Example: #####

colors.remove("Green") // colors: ["Red", "Blue", "Yellow"]

contains

Checks if the set contains a specific element.

Example: #####

if colors.contains("Blue") {
    print("Contains Blue!")
}
// Output: Contains Blue!

count

Returns the number of elements in the set.

Example: #####

let count = colors.count // count: 3

isEmpty

Checks if set is empty.

Example
if colors.isEmpty {
    print("The set is empty")
} else {
    print("The set is not empty")
}
// Output: The set is not empty

union

Combines two sets.

Example: #####

let moreColors: Set = ["Purple", "Yellow"]
let allColors = colors.union(moreColors) // allColors: ["Red", "Blue", "Yellow", "Purple"]

intersection

Finds elements that are common to two sets.

Example: #####

let commonColors = colors.intersection(moreColors) // commonColors: ["Yellow"]

subtracting

Removes an element of another set from one set.

Example: #####

let exclusiveColors = colors.subtracting(moreColors) // exclusiveColors: ["Red", "Blue"]

symmetricDifference

Finds elements in two sets that only exist in each other.

Example
let differentColors = colors.symmetricDifference(moreColors) // differentColors: ["Red", "Blue", "Purple"]

In what situations is set preferable?

It’s great for managing collections of unique elements, and for doing things similar to mathematical set operations.