class Solution {
func mostWordsFound(_ sentences: [String]) -> Int {
sentences.reduce(0) { max($0, numWords($1)) }
}
func numWords(_ string: String) -> Int {
string.reduce(1) { $0 + ($1 == " " ? 1 : 0) }
}
}
class Solution {
func mostWordsFound(_ sentences: [String]) -> Int {
sentences.reduce(0) { max($0, numWords($1)) }
}
func numWords(_ string: String) -> Int {
string.reduce(1) { $0 + ($1 == " " ? 1 : 0) }
}
}
函数式方法让您可以更紧凑、更清晰地编写循环,了解reduce函数的工作原理并通过示例对其进行分析。
您有一个初始值和一个处理每个元素的函数。而不是编写循环:
更方便的是看到我们有一个初始值和一个循环,每次都根据当前元素重新计算这个值,并在最后返回计算结果。
除了reduce,还有其他的功能,但是意思是一样的,缩短循环的写法,只描述元素上的动作。