How to add up sum of all core data entries

My code uses the attribute dx (saved as strings) from the entity Data using core data to save string entries. I would like to print the mean or average of all of the entries. So I have to convert all of the string to doubles then add them up and divide them by the amount of entries that are in the index. I just want to print this in the view did load function.

                     var itemName : [NSManagedObject] = []

      override func viewDidLoad() {


Hi @timswift, you could possibly try using compactMap. For example,

let stringArray = ["2","3","5"]
let doubleArray = stringArray.compactMap{ Double($0) }
let arraySum = doubleArray.reduce(0, +)

print(arraySum) //10

This would print out a total sum of 10 after converting the string array into a double array. I understand you are using Core Data entries so I’m not sure if this example would work but it could be worth trying.


This works but I am trying to get to get it to work using core data.

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