compactMap
compactMap is a higher-order function available on Swift’s Sequence and Collection types. It applies a transformation to each element and returns an array containing only the non-nil results. In effect, it combines mapping and filtering out nils in a single operation.
The usual form takes a closure that returns an optional value. For example, given a sequence of
Compared with map, which returns an array of the transformed values (possibly including nils if the transform
In practice, compactMap is often used to combine conversion and validation steps. Example: ["1","2","x","3"].compactMap { Int($0) } results
Relation to other operators: in modern Swift, compactMap is the dedicated method for removing nils produced