使用 reduce() 将 String 转换为 Int

Converting String to Int while using reduce()

我有代码:

let number: String = "111 15 111"
let result = number.components(separatedBy: " ").map {Int([=10=])!}.reduce(0, {[=10=] + })

首先,它接受给定的字符串并将其拆分为数字数组。接下来将每个数字转换为整数,最后将所有数字相加。它工作正常,但代码有点长。所以我想到了在使用 reduce 的同时使用 map 函数并将 String 转换为 Int 的想法,如下所示:

let result = number.components(separatedBy: " ").reduce(0, {Int([=11=])! + Int()!})

输出为:

error: cannot invoke 'reduce' with an argument list of type '(Int, (String, String) -> Int)'

因此我的问题是:为什么在使用 reduce() 时无法将 String 转换为 Integer?

reduce 第二个参数是一个闭包,[=13=] 是结果,</code> 是字符串。而不是强制展开可选的默认值会更好。</p> <pre><code>let number: String = "111 15 111" let result = number.components(separatedBy: " ").reduce(0, {[=10=] + (Int() ?? 0) })

另一种选择是使用 flatMapreduce 以及 + 运算符。

let result = number.components(separatedBy: " ").flatMap(Int.init).reduce(0, +)

你的错误是闭包中的第一个参数。如果您查看 reduce 声明,第一个闭包参数是 Result 类型,在您的情况下是 Int

public func reduce<Result>(_ initialResult: Result, 
    _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result

所以正确的代码是:

let result = number.components(separatedBy: " ").reduce(0, { [=11=] + Int()! })