Getting the sum of an array of doubles in swift

2019-06-10 11:10发布

问题:

I have an array of string numbers that I am fetching from core data and converting to doubles. I would like to get their sum once I've done this, but I get an error. I've tried it like this:

override func viewDidLoad() {
    super.viewDidLoad()

        //CoreData
        let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        let managedContext : NSManagedObjectContext = appDelegate.managedObjectContext!
        var fetchRequest = NSFetchRequest(entityName: "Log")
        fetchRequest.returnsObjectsAsFaults = false;
        var results: NSArray = managedContext.executeFetchRequest(fetchRequest, error: nil)!

        if (results.count > 0) {
            for res in results {
                var totalWorkTimeInHoursString = res.valueForKey("totalWorkTimeInHoursString")  as String
                //get double value of strings array
                var totalWorkTimeInHoursNSString = NSString(string: totalWorkTimeInHoursString)
                var totalWorkTimeInHoursNSStringDoubleValue = totalWorkTimeInHoursNSString.doubleValue
                lastLogHoursWorked.text = "\(totalWorkTimeInHoursString) hours"
                totalHoursWorkedSum.text = "\(totalWorkTimeInHoursNSStringDoubleValue)"

                let sum = totalWorkTimeInHoursNSStringDoubleValue.reduce(0,+)
                    //throws an error saying 'Double' does not have a member named 'reduce'

                println(totalWorkTimeInHoursNSStringDoubleValue)
                    //lists the array of doubles in console successfully
                println(sum)
                    //checking to see if 'sum' works properly

        }
        }else {
            println("zero results returned, potential error")
        }
}

Am I approaching this properly? what am I missing?

回答1:

Reduce is a function on an Array. When you say array.reduce(0, +), what you are saying is, "here's an array of doubles. Combine the elements into a single value by applying the + operation on the elements, starting with 0 as the value".

You cannot reduce a single value.



回答2:

Looking at your code, I deduce that results is an array of dictionaries, and each dictionary has a totalWorkTimeInHoursString key, whose value is a string representation of a double number.

I would solve it using a bit of functional approach, using filter, map and reduce:

if results.count > 0 {
    var res = results as [NSDictionary]

    var result = res.filter { $0["totalWorkTimeInHoursString"] is String }
        .map { ($0["totalWorkTimeInHoursString"] as NSString).doubleValue }
        .reduce (0, +)
}

What the code does:

  • convert the results array into an array of NSDictionary
  • filter the array by removing all elements (which are dictionaries) not having the totalWorkTimeInHoursString key, or whose corresponding value is not a string
  • convert each element of the array to a double, by extracting the value corresponding to the totalWorkTimeInHoursString key, converting to NSString and then to Double
  • apply the reduce method, passing the + operator to sum up the resulting array of Double

This is the data I tested my solution with, in a playground:

var results: NSArray = [
    ["totalWorkTimeInHoursString": "10.0"],
    ["totalWorkTimeInHoursString": "5.0"]
]