Filter

The filter function takes a function that, given an element in Array, returns Bool indicating whether the element should be included in the resulting Array. The filter method is declared as follows in Swift:

public func filter(@noescape includeElement: 
  (Self.Generator.Element) -> Bool) -> [Self.Generator.Element]

The definition is similar to the map method with the following differences:

  • The filter function takes a closure that receives elements of itself and returns a Bool value
  • The result of the filter method will be an array of its own type

Let's examine the following code to understand how it works:

let numbers = [10, 30, 91, 50, 100, 39, 74]
let evenNumbers = numbers.filter { $0 % 2 == 0 }

The resulting evenNumbers array will be [10, 30, 50, 100, 74].

Let's implement the filter function ourselves. In fact, its implementation is going to be similar to the implementation of map, except that it does not require a second generic specifying the codomain. Instead, it conditionally adds the original elements to the new Array:

func filter<Element> (elements: [Element], 
                      predicate:(Element -> Bool)) -> [Element] {
    var result = [Element]()
    for element in elements {
        if predicate(element) {
            result.append(element)
        }
    }
    return result
}

The filter function iterates through each element in our Array and applies the predicate to it. If the result of the predicate function becomes true, then element is added to our new Array. We can test our filter function as follows:

let filteredArray = filter(elements: numbers) { $0 % 2 == 0 }

The resulting array will be [10, 30, 50, 100, 74], which is identical to the Swift-provided filter method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset