Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
709 views
in Technique[技术] by (71.8m points)

ios - 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"]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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({ })


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...