Swiftly

Swift 5.1 references for busy coders

Sets

Sets store values of a certain type in an unordered list. Examples:

let numbers: Set<Int> = [1, 3, 5]
let planets: Set<String> = ["Mars", "Jupiter", "Earth"]

Mutability

Sets defined with var are mutable:

var planets: Set = ["Mars", "Jupiter", "Earth"]
planets.insert("Neptune")
planets.remove("Earth")
print(planets) // ["Mars", "Neptune", "Jupiter"]

Type

The type of a set’s elements is not required:

let numbers: Set = [1, 3, 5] // Inferred to be type Set<Int>
let planets: Set = ["Mars", "Jupiter", "Earth"] // Inferred to be Set<String>

But the type can also be explicitly declared:

let numbers: Set<Int> = [1, 3, 5]
let planets: Set<String> = ["Mars", "Jupiter", "Earth"]

Iteration and manipulation

Sets can be iterated over using for-in. They can be manipulated using map, flatMap, and reduce. They can be sorted into an array using sorted.