在Swift3中的数组过滤器 [英] Array filter in Swift3
问题描述
$ p $
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]
如果我们接着这个代码的部分:
$ b $ pre $ let wordFreqs = [(k,5),(a,7),(b,3)]
你从一个元组的数组开始。
从Swift文档中:
元组类型是逗号分隔的类型列表,用括号括起来。
和:
元组将多个值组合为一个复合值。元组中的值可以是任何类型。
在这种情况下,元组是2个值的连接类型字符串和1类型的Int。
let res = wordFreqs.filter
{
(e) - > Bool in
这部分适用在这里你可以看到过滤器的闭包接受了一个元素e(在我们的例子中是一个元组),并返回一个Bool。使用'filter'函数返回true意味着保持该值,while
if e.1> 3 {
返回true
} else {
返回false
}
e.1
语法返回索引1中元组的值。
因此,如果索引为1(第二个)的元组值为超过3,过滤器返回true(所以t将保留uple);如果不是,过滤器返回false(因此从结果中排除元组)。
在这一点上,过滤器的结果将是 [(k,5),(a,7)]
})。map {$ 0.0}
pre>
map函数根据元组数组创建一个新的数组:对于输入数组的每个元素($ 0),它返回索引为0的元组值。新阵列是
[k,a]
print(res)
控制台。
这些函数(filter,map,reduce等)在函数式编程中非常常见。
它们通常使用点语法链接,例如[1,2,3] .filter({})。map({})。reduce({})
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:
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({ })
这篇关于在Swift3中的数组过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!