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 missingBuilding a set from an array de-duplicates in one step:
let unique = Set([1, 2, 2, 3, 3, 3])
// 3 elements, exact order not guaranteedChallenge
BeginnerRead a single line of input: a comma-separated list of words (possibly with duplicates).
Print three lines:
- The number of unique words (use
Set) - The unique words sorted alphabetically, joined with
, truewhen the input contains the wordswift, otherwisefalse(usecontains)
For input swift,ruby,go,swift,go,rust, the output is:
4
go,ruby,rust,swift
trueCheat 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 missingBuild a set from an array to de-duplicate:
let unique = Set([1, 2, 2, 3, 3, 3]) // 3 elementsTry it yourself
let words = readLine()!.components(separatedBy: ",")
// TODO: dedupe via Set, print count, sorted joined, contains "swift"
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
Count and IndicesCase and TrimSearching in StringsSplitting and JoiningReplacing SubstringsRecap - Username Check