将字符串数组转换为双精度,然后在 Swift 中计算总和 [英] Converting Array Of String to Double and then calculating the sum in Swift

查看:12
本文介绍了将字符串数组转换为双精度,然后在 Swift 中计算总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串数组,我想将其转换为 Double.然后我想将数组中的每个项目加在一起并得到总和.

I have an array of Strings that i would like to convert to Double. Then i would like to add each item in the array together and get the sum.

到目前为止,这是我的代码,在枚举数组后,我在将它们添加在一起时遇到了问题.

this is my code so far, After enumerating the array I'm having issues adding all of them together.

推荐答案

更新:Xcode 10.1 • Swift 4.2.1 或更高版本

let strings = ["1.9","2.7","3.1","4.5","5.0"]
let doubles = strings.compactMap(Double.init)
let sum = doubles.reduce(0, +)

print(sum) // 17.2


如果不需要中介集合


If you dont need the intermediary collection

let sum = strings.reduce(0) { $0 + (Double($1) ?? .zero) }

这篇关于将字符串数组转换为双精度,然后在 Swift 中计算总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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