2015-09-03 99 views

回答

4

您可以使用地圖的方法來你的元素轉換爲的NSString和訪問它的doubleValue財產,並用減少方法結合起來,總結所產生的雙陣列如下:

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 

更新: 的Xcode 7.1.1•斯威夫特2.1

您可以使用雙(字符串:)初始化器:

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

print(arraySum) // 17.2 
+2

僅有代碼的答案不是很有幫助。請包括一些解釋! – jtbandes

0

這裏是一個答案,在雨燕2.0的你問題的第一部分:

我有我想轉換到雙字符串數組。然後我想將數組中的每個項目一起添加並獲得總和。

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 
}) 
1

循環通過陣列, 對於每個字串,轉換字符串使用加倍:

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) 
1

僅有map(迭代並將數組中的每個值)將數組中的所有值寫入Double,然後將reduce a將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" 
相關問題