使用reduce()时将String转换为Int [英] Converting String to Int while using reduce()

查看:58
本文介绍了使用reduce()时将String转换为Int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有代码:

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

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

First it takes given string and split into array of numbers. Next each number is converted to an integer and at the end all numbers are added to each other. It works fine but code is a little bit long. So I got the idea to get ride of map function and convert String to Int while using reduce, like this:

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?

Thus my question is: Why I cannot convert String to Integer while using reduce()?

推荐答案

reduce 第二个参数是一个闭包,$0 是结果,$1> 是字符串.而不是强制解包可选的默认值会更好.

reduce second parameter is a closure with $0 is the result and $1 is the string. And instead of force unwrapping optional default value will be better.

let number: String = "111 15 111"
let result = number.components(separatedBy: " ").reduce(0, {$0 + (Int($1) ?? 0) })

另一种选择是使用 flatMapreduce+ 运算符.

Another alternative is with flatMap and reduce with + operator.

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

这篇关于使用reduce()时将String转换为Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆