快速获得一系列双打的总和

时间:2014-12-05 18:04:34

标签: arrays core-data swift double reduce

我有一个字符串数组,我从核心数据中获取并转换为双精度数。一旦我做完了,我想得到他们的总和,但我得到一个错误。我试过这样的话:

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

我接近这个吗?我错过了什么?

2 个答案:

答案 0 :(得分:3)

ReduceArray上的函数。当你说array.reduce(0, +)时,你说的是,"这里是一系列双打。通过对元素应用+操作将元素组合成单个值,从0开始作为值"。

您不能reduce单个值。

答案 1 :(得分:3)

查看代码,我推断results是一个字典数组,每个字典都有一个totalWorkTimeInHoursString键,其值是双数字的字符串表示形式。

我会使用一些功能方法解决它,使用filtermapreduce

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

代码的作用:

  • results数组转换为NSDictionary
  • 数组
  • 通过删除没有totalWorkTimeInHoursString键或其对应值不是字符串的所有元素(字典)来过滤数组
  • 通过提取与totalWorkTimeInHoursString键对应的值,转换为NSString然后转换为Double
  • ,将数组的每个元素转换为double
  • 应用reduce方法,通过+运算符对Double的结果数组进行总结

这是我在游乐场测试我的解决方案的数据:

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