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

查看:149
本文介绍了将字符串数组转换为Double,然后在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


Xcode 7.1.1•Swift 2.1

您可以使用Double(string :)初始化程序:

You can use Double(string:) initialiser:

let stringArray = ["1.9","2.7","3.1","4.5","5.0"]
let doubleArray = stringArray.flatMap(Double.init) 
let arraySum = doubleArray.reduce(0, combine: +)

print(arraySum) // 17.2


Swift 1.x

您可以使用map方法将您的元素转换为NSString并访问其doubleValue属性,并将其与reduce方法组合以对所得的double数组求和,如下所示:

You can use map method to convert your elements to NSString and access its doubleValue property and combine it with a reduce method to sum the resulting double array as follow:

let stringArray = ["1.9","2.7","3.1","4.5","5.0"]
let doubleArray = stringArray.map{ NSString(string: $0).doubleValue }
let arraySum = doubleArray.reduce(0, combine: +)

println(arraySum) // 17.2

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

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