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)
给出输出:
["k","a"]
推荐答案
如果我们一个接一个地处理这段代码:
If we take the parts of this code one after the other:
let wordFreqs = [("k", 5), ("a", 7), ("b", 3)]
您从一组元组开始.
来自 Swift 文档:
From the Swift documentation:
元组类型是以逗号分隔的类型列表,括在括号中.
A tuple type is a comma-separated list of types, enclosed in parentheses.
和:
元组将多个值分组为一个复合值.元组中的值可以是任何类型.
Tuples group multiple values into a single compound value. The values within a tuple can be of any type.
在这种情况下,元组是 2 个值的一对",一个是 String 类型,另一个是 Int 类型.
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
这部分在数组上应用过滤器.您可以在此处看到过滤器的闭包采用元素 e(因此,在我们的示例中为一个元组),并返回一个 Bool.使用 'filter' 函数,返回 true 表示保留该值,而返回 false 表示将其过滤掉.
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
}
e.1
语法返回索引 1 处元组的值.因此,如果索引 1(第二个)处的元组值超过 3,则过滤器返回 true(因此元组将被保留);如果不是,过滤器返回 false(因此从结果中排除元组).此时,过滤器的结果将是 [("k", 5), ("a", 7)]
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 }
map 函数基于元组数组创建一个新数组:对于输入数组 ($0) 的每个元素,它返回索引 0 处的元组值.所以新数组是 ["k", "一个"]
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.
这些函数(filter、map、reduce 等)在函数式编程中非常常见.它们通常使用点语法链接,例如 [1, 2, 3].filter({ }).map({ }).reduce({ })
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({ })
这篇关于Swift3 中的数组过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!