我有一个字符串数组,我从核心数据中获取并转换为双精度数。一旦我做完了,我想得到他们的总和,但我得到一个错误。我试过这样的话:
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")
}
}
我接近这个吗?我错过了什么?
答案 0 :(得分:3)
Reduce
是Array
上的函数。当你说array.reduce(0, +)
时,你说的是,"这里是一系列双打。通过对元素应用+
操作将元素组合成单个值,从0开始作为值"。
您不能reduce
单个值。
答案 1 :(得分:3)
查看代码,我推断results
是一个字典数组,每个字典都有一个totalWorkTimeInHoursString
键,其值是双数字的字符串表示形式。
我会使用一些功能方法解决它,使用filter
,map
和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, +)
}
代码的作用:
results
数组转换为NSDictionary
totalWorkTimeInHoursString
键或其对应值不是字符串的所有元素(字典)来过滤数组totalWorkTimeInHoursString
键对应的值,转换为NSString
然后转换为Double
reduce
方法,通过+
运算符对Double
的结果数组进行总结这是我在游乐场测试我的解决方案的数据:
var results: NSArray = [
["totalWorkTimeInHoursString": "10.0"],
["totalWorkTimeInHoursString": "5.0"]
]