Menu
Coddy logo textTech

Creating Sets

Part of the Logic & Flow section of Coddy's Swift journey — lesson 18 of 56.

A Set is an unordered collection of unique values. Same element type for every member, no duplicates allowed, no predictable iteration order.

var colors: Set<String> = ["red", "green", "blue", "red"]
print(colors.count)              // 3 (the duplicate "red" is dropped)

The type annotation Set<String> is mandatory in the literal form because ["a", "b"] on its own would be inferred as an Array.

Three core operations: contains, insert, and remove. The latter two return information about whether the change was meaningful.

colors.insert("yellow")         // adds it
colors.insert("red")            // already there, no effect
colors.contains("green")        // true
colors.remove("blue")           // returns "blue" or nil if missing

Building a set from an array de-duplicates in one step:

let unique = Set([1, 2, 2, 3, 3, 3])
// 3 elements, exact order not guaranteed
challenge icon

Challenge

Beginner

Read a single line of input: a comma-separated list of words (possibly with duplicates).

Print three lines:

  1. The number of unique words (use Set)
  2. The unique words sorted alphabetically, joined with ,
  3. true when the input contains the word swift, otherwise false (use contains)

For input swift,ruby,go,swift,go,rust, the output is:

4
go,ruby,rust,swift
true

Cheat sheet

Set – unordered collection of unique values. Type annotation required when using array literal syntax:

var colors: Set<String> = ["red", "green", "blue", "red"]
print(colors.count) // 3 (duplicate dropped)

Core operations:

colors.insert("yellow")      // adds element
colors.contains("green")     // true
colors.remove("blue")        // returns "blue" or nil if missing

Build a set from an array to de-duplicate:

let unique = Set([1, 2, 2, 3, 3, 3]) // 3 elements

Try it yourself

let words = readLine()!.components(separatedBy: ",")

// TODO: dedupe via Set, print count, sorted joined, contains "swift"
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow