Files
swift-algorithms/Guides/Compacted.md
T

1.4 KiB

Compacted

[Source | Tests]

Convenience method that flatten the nils out of a sequence or collection. That behaves exactly one of the most common uses of compactMap which is collection.lazy.compactMap { $0 } which is only remove nils without transforming the elements.

let array: [Int?] = [10, nil, 30, nil, 2, 3, nil, 5]
let withNoNils = array.compacted()
// Array(withNoNils) == [10, 30, 2, 3, 5]

The most convenient part of compacted() is that we avoid the usage of a closure.

Detailed Design

The compacted() methods has two overloads:

extension Sequence {
  public func compacted<Unwrapped>() -> CompactedSequence<Self, Unwrapped> { ... }
}

extension Collection {
  public func compacted<Unwrapped>() -> CompactedCollection<Self, Unwrapped> { ... }
}

One is a more general CompactedSequence for any Sequence base. And the other a more specialized CompactedCollection where base is a Collection and with conditional conformance to BidirectionalCollection, RandomAccessCollection and LazyCollectionProtocol when base collection conforms to them.

Naming

The naming method name compacted() matches the current method compactMap that one of the most common usages compactMap { $0 } is abstracted by it.