Search code examples
arraysswiftparse-platform

Converting Array Of String to Double and then calculating the sum in Swift


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.

enter image description here

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

enter image description here


Solution

  • update: Xcode 10.1 • Swift 4.2.1 or later

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