'how to calculate the sum of a value in a table view and to display it in a separate label

I have successfully created a core data file and linked it to my tableview and a view controller. The data model is as follows

import Foundation
import CoreData

@objc(Aktie)

class Aktie: NSManagedObject

{

    @NSManaged var title: String?
    @NSManaged var point: String?
}

Now I am trying to calculate the sum of "point" into a separate textField of my tableView, but i also tried to build a new viewcontroller with a textField I am using the following code in the new viewController to get the info from core data. I do not know if this ios necessary. I am also using firstLoad in other files.

import UIKit
import CoreData

var points = [Aktie]()
var firstLoad = true

class TotalPointsViewController: UIViewController {
    @IBOutlet weak
    var totalPoints: UILabel!

      override func viewDidLoad() {
        super.viewDidLoad()
        if (firstLoad) {
          firstLoad = false
          let appDelegate = UIApplication.shared.delegate as!AppDelegate
          let context: NSManagedObjectContext = appDelegate.persistentContainer.viewContext
          let request = NSFetchRequest < NSFetchRequestResult > (entityName: "Aktie")
          do {
            let results: NSArray =
              try context.fetch(request) as NSArray
            for result in results {
              let aktie = result as!Aktie
              points.append(aktie)
            }
          } catch {
            print("Fetch Failed")
          }
        }
      }

The code for the calculation is as follows.

func calculateSumPoints() {
  let sum=points.compactMap {
    $0.point
  }
  .reduce(0) {
    previous,
    next in guard let value=Int(next) else {
      return previous
    }
    return previous+value
  }
  totalPoints.text="\(sum)"
}

I also tried the following code.

func calculateSumPoints() {
  var sum = 0
  for punt in points {
    sum += Int(punt.point ? ? "0") ? ? 0
  }
  totalPoints.text = "\(sum)"
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source