我有代码:
let number: String = "111 15 111"
let result = number.components(separatedBy: " ").map {Int($0)!}.reduce(0, {$0 + $1})
首先,它接受给定的字符串并将其拆分为数字数组。接下来将每个数字转换为整数,最后将所有数字相加。它工作正常,但代码有点长。所以我想到了在使用 reduce 的同时使用 map 函数并将 String 转换为 Int,如下所示:
let result = number.components(separatedBy: " ").reduce(0, {Int($0)! + Int($1)!})
输出是:
error: cannot invoke 'reduce' with an argument list of type '(Int, (String, String) -> Int)'
因此我的问题是:为什么在使用 reduce() 时无法将 String 转换为 Integer?
最佳答案
reduce
第二个参数是一个闭包,$0
是结果,$1
是字符串。而不是强制展开可选的默认值会更好。
let number: String = "111 15 111"
let result = number.components(separatedBy: " ").reduce(0, {$0 + (Int($1) ?? 0) })
另一种选择是使用 flatMap
和使用 +
运算符的 reduce
。
let result = number.components(separatedBy: " ").flatMap(Int.init).reduce(0, +)
关于swift - 使用 reduce() 将 String 转换为 Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49477947/