How do I sum an array of string values

let array = [“20.00”, “40.00”, “1000.00”]
//1060

I tried this but once the number is greater than 999.00 it doesn’t sum.

let sum = array.reduce(0.0, {$0 + (Float($1) ?? 0.0)})

Hi jport1130,

I tries to replicate the issue but could not find the error as you described, it just worked for me.

However, if this were not to work, there are a couple of things here that I wanted to talk about, “in my opinion…”

  1. If you have an array of strings, then a better way to handle it is to first transform them into an array of integers, which you could use map, but flatmap is better in this case as it will skip the nils.
  2. Any particular reason to use Float? I would use Doubles instead because the system has better support for Doubles

if you get stuck, please respond to this and let’s have a detailed look at the same,

Enjoy your holidays and have a happy new year.

Cheers,

Jayant

Jayant,
Thank you for your response, I appreciate the help. The array I have shown you is an array of subtotals. I take the quantity x cost and calculate the subtotal. Then I am trying to sum all of the subtotals into a total. Being new to this I thought I had to use a string since I was entering the values through a UITextField, but maybe I am incorrect? I used float as I am dealing with dollars and cents and need the decimal places, but maybe I am incorrect again? After reading your response I wonder if I am implementing the code correctly. I was creating a separate array of subtotals to calculate the total. Is a separate array needed if the values are already within an array of objects? Thanks again for all your help! Happy Holidays to you, and Happy New Year!

Hi @jport1130,
A quick response to your question. Have a look at Functional Programming, there is a wonderful article on this site that can be found at https://www.raywenderlich.com/157123/introduction-functional-programming-swift-2 by Niv.

You can also transform the text from a UITextField to the desired form at any stage, either on entry or while processing, though keeping it in the form that you would use it most is the way to go.

Swift makes it easy to work with arrays, you can combine them or transform them as required easier than with other C type or Java type languages.

If you post what you are trying to do, can provide you a hint or direction of a better way (if any)

cheers,

Jayant

The phrase “it doesn’t sum” is an unacceptable way to describe a computer programming issue. It’s equivalent to saying, “My code doesn’t work!”. You need to post your code, but you also need to post the actual result or any errors and state your desired result. You did post your code, and you did post your desired result–but you did not post the actual result/errors you got.

The code you posted does not “work” for me. (See what I did there?)

Thanks Jayant, I appreciate your response!

This topic was automatically closed after 166 days. New replies are no longer allowed.