简体   繁体   English

Swift3中的数组过滤器

[英]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"]

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: 从Swift文档:

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. 在这种情况下,元组是2个值的“耦合”,一个是String类型,另一个是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. 你可以在这里看到过滤器的闭包需要一个元素e(所以,在我们的例子中,是一个元组),然后返回一个Bool。 With the 'filter' function, returning true means keeping the value, while returning false means filtering it out. 使用'filter'函数,返回true表示保留值,而返回false表示将其过滤掉。


            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) ; e.1语法返回索引1处元组的值。因此,如果索引1(第二个)的元组值超过3,则过滤器返回true(因此将保留元组); if not, the filter returns false (and therefore excludes the tuple from the result). 如果不是,则过滤器返回false(因此从结果中排除元组)。 At that point, the result of the filter will be [("k", 5), ("a", 7)] 此时,过滤器的结果将是[("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"] map函数基于元组数组创建一个新数组:对于输入数组的每个元素($ 0),它返回索引0处的元组值。所以新数组是["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({ }) 它们通常使用点语法链接,例如, [1, 2, 3].filter({ }).map({ }).reduce({ })

// this creates an array of tuples
let wordFreqs = [("k", 5), ("a", 7), ("b", 3)]

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

    // this filters the array
    // it removes any items that have the second part of the tuple
    // of 3 or less
    if e.1 > 3 {
        return true
    } else {
        return false
    }
}.map {
    // this "maps" the array and returns the first part of the tuple
    $0.0
}

print(res)

Note... if I was writing this I would shorten it to something like... 注意......如果我写这篇文章,我会把它缩短为......

let res = wordFreqs.filter { $0.1 > 3 }
                   .map { $0.0 }

wordFreqs is array of tuple . wordFreqstuple数组。

Tuples 元组

A tuple is a group of zero or more values represented as one value. 元组是表示为一个值的零个或多个值的组。

For example ("John", "Smith") holds the first and last name of a person. 例如 (“John”,“Smith”)拥有一个人的名字和姓氏。 You can access the inner values using the dot(.) notation followed by the index of the value: 您可以使用点(。)表示法后跟值的索引来访问内部值:

var person = ("John", "Smith")

var firstName = person.0 // John
var lastName = person.1 // Smith

Now in your case you have tuple with type (String, Int) and with filter you are comparing the e.1 > 3 (Here e is holds the tuple value from the array iteration with filter ) means thats second(Int) value is greater than 3. 现在在你的情况下你有一个类型(String, Int)元组和你正在比较e.1 > 3 filter (这里e是保持带有filter的数组迭代的元组值)意味着second(Int)值更大比3。

Now after that your using map on the filter result and just retuning the String($0.0) from the tuple. 之后,您在filter结果上使用map ,并从元组重新调整String($0.0)

    //array of tuples
    let wordFreqs = [("k", 5), ("a", 7), ("b", 3)]

    let res = wordFreqs.filter(
    {
        (e) -> Bool in
        //Comparing the Second Int value of tuple in filter
        if e.1 > 3 {
            return true
        } else {
            return false
        }

    })
    //Mapping the result of filter
    .map { 
         //return the String from the tuple
         $0.0 
    }

Your e object representing (String, int) type. 您的e对象表示(String, int)类型。 As you can see in array inside [("k", 5), ("a", 7), ("b", 3)] . 正如你在[("k", 5), ("a", 7), ("b", 3)]中的数组中看到的那样。

First of all you are using filter method so that's why you have to return true or false values. 首先,您使用的是filter方法,这就是您必须返回truefalse值的原因。 In this case you check if e.1 (means int value) is greater than 3, if not you return false. 在这种情况下,您检查e.1 (表示int值)是否大于3,否则返回false。 After all that process the filter method return filtered array of (String,int) objects. 在所有这个过程之后, filter方法返回(String,int)对象的过滤数组。

Next step is map function. 下一步是map功能。 In your case is simple it is just map all array values to first object of your tuple (String, int). 在你的情况下很简单,它只是将所有数组值映射到元组的第一个对象(String,int)。

To understand better your code could look like this: 为了更好地理解您的代码可能如下所示:

let filteredArray = wordFreqs.filter
({
    (e) -> Bool in
    return e.1 > 3
})// the filteredArray is [("k", 5), ("a", 7)]


let finalValue = filteredArray.map { 
  $0.0
}// here you're creating a new array with String. $0 represents object from filteredArray

print(finalValue) // ["k", "a"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM