2015-08-07 Core Data sum example

I had some trouble last week finding a Swift example to sum across order line entities in Core Data. In the app I'm working on, there's the usual Order and OrderLine entities, and they're exactly what you think they are: clients can use the app to shop, and when they put stuff in their shopping cart, we slowly build an order with order lines.

Note 1: in the code below, order lines are called order items because "legacy".

Note 2: the predicate in the fifth line passes self as the order. That works in our case, because the function is located in the Order class. Adjust as necessary.

Without further ado:

	func orderItemsQuantity(managedObjectContext: NSManagedObjectContext) -> Int {
		let quantityExpression = NSExpressionDescription()
		quantityExpression.name = "totalQuantity"
		quantityExpression.expression = NSExpression(format: "@sum.quantity")
		quantityExpression.expressionResultType = .Integer32AttributeType
		
		let predicate = NSPredicate(format: "order == %@", self)
		
		let request = NSFetchRequest()
		request.entity = NSEntityDescription.entityForName("OrderItem", inManagedObjectContext: managedObjectContext)
		request.propertiesToGroupBy = ["order"]
		request.resultType = NSFetchRequestResultType.DictionaryResultType
		request.propertiesToFetch = [quantityExpression]
		request.predicate = predicate
		
		var results:[[String:AnyObject]]?
		var error: NSError? = nil
		var totalQuantity = 0
		if let results = managedObjectContext.executeFetchRequest(request, error: &error) as? [[String:AnyObject]] {
			if error != nil {
				fatalError("Unresolved error \(error), \(error!.userInfo)")
			}
			if let totalQuantityDict = results.first {
				if let totalQuantityResult: AnyObject = totalQuantityDict["totalQuantity"] {
					totalQuantity = totalQuantityResult as! Int
				}
			}
		}
		return totalQuantity
	}