答案 0 :(得分:4)
更新: 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 :)初始值:
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数组求和,如下所示:
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
答案 1 :(得分:1)
循环遍历数组, 对于每个字符串,使用以下命令将字符串转换为double:
Double(string:String)
然后将每个添加到计数
var strings:[String] = ["1.3", "1", "8", "5", "bad number"]
var tally = 0.0
for eachString in strings{
// Convert each string to Double
if let num = Double(eachString) { //Double(String) returns an optional.
tally += num
} else {
print("Error converting to Double")
}
// Another way to convert if you don't need error handling
// NSString.doubleValue will just return 0.0 on a bad string.
// let num=(eachString as NSString).doubleValue
// tally += num
}
print(tally)
答案 2 :(得分:1)
只需map
(迭代并转换数组中的每个值)数组中的所有值都为Double
,然后reduce
所有Double
值,其值为0
和闭包(在你的情况下,它只是一个操作员)+
。
通过递归应用提供的闭包,
reduce
一个元素集合,直到单个值。
let stringDoubles = ["2.9","3.1","1.7","9.5","5.6"]
let sum = stringDoubles.map { Double($0)! }.reduce(0, combine: +)
print(sum) // "22.8". If start value was, for example, 10, print(sum) => "32.8"
答案 3 :(得分:0)
以下是您在Swift 2.0中的第一部分问题的答案:
我有一个字符串数组,我想转换为Double。然后我想将数组中的每个项目一起添加并得到总和。
let myStrings = ["2", "3","5.6", "4", "6"]
let doubles = myStrings.map { (s : String) -> Double in
if let d = Double(s){
return d
}
return 0.0
}
let sum = doubles.reduce(0.0, combine: {(sum: Double, item:Double) ->Double in
return sum + item
})