concept filter in category swift

appears as: filter
Swift in Depth

This is an excerpt from Manning's book Swift in Depth.

  • Sequence is the backbone for methods such as filter, reduce, map, zip, repeat, and many others.
  • 12.7.1. Looking under the hood of filter

    Before extending Sequence, let’s take a closer look at a few interesting things regarding how Swift does it. First, filter accepts a function. This function is the closure you pass to filter.

    Listing 12.24. A small filter method
    let moreThanOne = [1,2,3].filter { (int: Int) in
      int > 1
    }
    print(moreThanOne) // [2, 3]

    Looking at the signature of filter, you can see that it accepts a function, which makes filter a higher-order function. A higher-order function is a ten-dollar concept for a one-dollar name, indicating that a function can accept or return another function. This function is the closure you pass to filter.

    Also note that filter has the rethrows keyword as showing in listing 12.25. If a function or method rethrows, any errors thrown from a closure are propagated back to the caller. Having a method with rethrows is similar to regular error propagation, except rethrows is reserved for higher-order functions, such as filter. The benefit of this is that filter accepts both nonthrowing and throwing functions; it’s the caller that has to handle any errors.

    Listing 12.25. Looking at filter's signature
    public func filter(
        _ isIncluded: (Element) throws -> Bool    #1
       ) rethrows -> [Element] {                  #2
         // ... snip
    }

    Now, let’s look at the body. You can see that filter creates a results array, which is of the obscure type called ContiguousArray—more on that in a minute—and iterates through each element via the low-level, no-overhead makeIterator method. For each element, filter calls the isIncluded method, which is the closure you pass to filter. If isIncluded—also known as the passed closure—returns true, then filter appends the element to the results array.

    Finally, filter converts the ContiguousArray back to a regular Array.

    Listing 12.26. Looking at filter
    public func filter(
        _ isIncluded: (Element) throws -> Bool       #1
       ) rethrows -> [Element] {
        var result = ContiguousArray<Element>()      #2
     
        var iterator = self.makeIterator()           #3
     
        while let element = iterator.next() {        #3
           if try isIncluded(element) {              #4
             result.append(element)                  #5
           }
        }
    
        return Array(result)                         #6
     }