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"]
Your
e
object representing(String, int)
type. As you can see in array inside[("k", 5), ("a", 7), ("b", 3)]
.First of all you are using
filter
method so that's why you have to returntrue
orfalse
values. In this case you check ife.1
(means int value) is greater than 3, if not you return false. After all that process thefilter
method return filtered array of (String,int) objects.Next step is
map
function. In your case is simple it is just map all array values to first object of your tuple (String, int).To understand better your code could look like this:
Note... if I was writing this I would shorten it to something like...
wordFreqs
is array oftuple
.Tuples
For example ("John", "Smith") holds the first and last name of a person. You can access the inner values using the dot(.) notation followed by the index of the value:
Now in your case you have tuple with type
(String, Int)
and withfilter
you are comparing thee.1 > 3
(Heree
is holds the tuple value from the array iteration withfilter
) means thatssecond(Int)
value is greater than 3.Now after that your using
map
on thefilter
result and just retuning theString($0.0)
from the tuple.If we take the parts of this code one after the other:
You start with an array of tuples.
From the Swift documentation:
and:
In this case, the tuples are "couples" of 2 values, one of type String and 1 of type Int.
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.
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)]
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"]
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({ })