如何获得总和核心数据Swift3

时间:2017-03-21 04:58:10

标签: ios core-data swift3

import Foundation
import CoreData
import UIKit

class CoreDataManager5: NSObject {

    private class func getContext() -> NSManagedObjectContext{
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        return appDelegate.persistentContainer.viewContext
    }
    class func fetchObj() -> [foodItem]{
        var array = [foodItem]()
        let fetchRequest: NSFetchRequest<FoodS5N5> = FoodS5N5.fetchRequest()
        do{
            let fetchResults = try getContext().fetch(fetchRequest)
            print(fetchResults)

            for food in fetchResults{
                let foods = foodItem(foodCalorie5: food.foodCalorie5!)
                array.append(foods)

                var addFood:[String] = []
                addFood.append(foods.foodCalorie5!)
                print(addFood)

                let sumArray:[String] = addFood
                let sumArrayofInt: [Int] = sumArray.map{Int($0) ?? 0}
                let sum = sumArrayofInt.reduce(0,+)
                print("Food calorie = \(sum)")

            }
        }catch{
            //show error
        }
        return array
    }
}

struct foodItem {
    var foodCalorie5:String?
    init() {
        foodCalorie5 = ""
    }
    init(foodCalorie5:String){
        self.foodCalorie5 = foodCalorie5
    }
}

Screenshot

1 个答案:

答案 0 :(得分:0)

您需要计算sum循环之外的for

var array = [foodItem]()
for food in fetchResults{
    let foods = foodItem(foodCalorie5: food.foodCalorie5!)
    array.append(foods)
}
let calories = array.flatMap { Int($0.foodCalorie5!) }
let sum = calories.reduce(0, +)
print("Food calorie = \(sum)")