Filtering
Remove duplicated elements or strip the nil
values from a sequence or collection.
Overview
Use the uniquing methods to remove duplicates from a sequence or collection, or to remove elements that have a duplicated property.
let numbers = [1, 2, 3, 3, 2, 3, 3, 2, 2, 2, 1]
let unique = numbers.uniqued()
// Array(unique) == [1, 2, 3]
The compacted()
method removes all nil
values from a sequence or collection of optionals:
let array: [Int?] = [10, nil, 30, nil, 2, 3, nil, 5]
let withNoNils = array.compacted()
// Array(withNoNils) == [10, 30, 2, 3, 5]
Uniquing Elements
func uniqued(
) -> UniquedSequence<Self, Element> Returns a sequence with only the unique elements of this sequence, in the order of the first occurrence of each unique element.
func uniqued<Subject>(on: (Element) throws -> Subject
) rethrows -> [Element] Returns an array with the unique elements of this sequence (as determined by the given projection), in the order of the first occurrence of each unique element.
func uniqued<Subject>(on: @escaping (Element) -> Subject
) -> UniquedSequence<Self, Subject> Returns a lazy sequence with the unique elements of this sequence (as determined by the given projection), in the order of the first occurrence of each unique element.
Filtering out nil
Elements
func compacted<Unwrapped>(
) -> CompactedCollection<Self, Unwrapped> Returns a new
Collection
that iterates over every non-nil element from the originalCollection
.func compacted<Unwrapped>(
) -> CompactedSequence<Self, Unwrapped> Returns a new
Sequence
that iterates over every non-nil element from the originalSequence
.
Supporting Types
struct UniquedSequence<Base, Subject>
A sequence wrapper that leaves out duplicate elements of a base sequence.
struct CompactedSequence<Base, Element>
A
Sequence
that iterates over every non-nil element from the originalSequence
.struct CompactedCollection<Base, Element>
A
Collection
that iterates over every non-nil element from the originalCollection
.