Swiftly

Swift 5.6 references for busy coders

Sets

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

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

Sets do not guarantee a specific order, and each value can appear only once:

let numbers: Set<Int> = [1, 3, 5, 5, 5]
print(numbers) // [3, 1, 5]

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.

See also

Further reading