Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array filter in Swift3

I have a piece of code. I am not getting whats going inside in this code. Can anybody explain it?

 let wordFreqs = [("k", 5), ("a", 7), ("b", 3)]

        let res = wordFreqs.filter(
        {
            (e) -> Bool in

            if e.1 > 3 {
                return true
            } else {
                return false
            }

        }).map { $0.0 }

        print(res)

Gives Output:

["k","a"]
like image 458
Amanpreet Avatar asked Nov 30 '22 09:11

Amanpreet


1 Answers

If we take the parts of this code one after the other:

let wordFreqs = [("k", 5), ("a", 7), ("b", 3)]

You start with an array of tuples.

From the Swift documentation:

A tuple type is a comma-separated list of types, enclosed in parentheses.

and:

Tuples group multiple values into a single compound value. The values within a tuple can be of any type.

In this case, the tuples are "couples" of 2 values, one of type String and 1 of type Int.


        let res = wordFreqs.filter(
        {
            (e) -> Bool in

This part applies a filter on the array. You can see here that the closure of the filter takes an element e (so, in our case, one tuple), and returns a Bool. With the 'filter' function, returning true means keeping the value, while returning false means filtering it out.


            if e.1 > 3 {
                return true
            } else {
                return false
            }

The e.1 syntax returns the value of the tuple at index 1. So, if the tuple value at index 1 (the second one) is over 3, the filter returns true (so the tuple will be kept) ; if not, the filter returns false (and therefore excludes the tuple from the result). At that point, the result of the filter will be [("k", 5), ("a", 7)]


        }).map { $0.0 }

The map function creates a new array based on the tuple array: for each element of the input array ($0), it returns the tuple value at index 0. So the new array is ["k", "a"]


        print(res)

This prints out the result to the console.


These functions (filter, map, reduce, etc.) are very common in functional programming. They are often chained using the dot syntax, for example, [1, 2, 3].filter({ }).map({ }).reduce({ })

like image 125
Frédéric Adda Avatar answered Dec 04 '22 02:12

Frédéric Adda