我有一個字符串數組數組,我從核心數據中提取並轉換爲雙精度數。一旦我完成了這個任務,我希望得到他們的總和,但是我得到一個錯誤。我試過這樣:在swift中獲取數組的總和
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")
}
}
我是否正確地接近這個?我錯過了什麼?
根據該docs(https://developer.apple.com/library/mac/documentation/General/Reference/SwiftStandardLibraryReference/Array.html)'reduce'應用於* collection * - 不是double。 – 2014-12-07 16:37:38