ios - 查找表格 View 中所有数字的平均值

标签 ios core-data tableview swift4 mean

下面的代码列出了表格 View 上的数字。我想要做的就是打印 View did load 函数中数字的平均值。 TableView 从核心数据模型获取其数字。

        var scores = UITableView()
    var itemName : [NSManagedObject] = []
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return itemName.count


}


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let title = itemName[indexPath.row]
        let cell = scores.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath)
        cell.textLabel?.text = title.value(forKey: "ee") as? String
        cell.textLabel?.textAlignment = .center


        cell.preservesSuperviewLayoutMargins = false
        cell.separatorInset = UIEdgeInsets.zero
        cell.layoutMargins = UIEdgeInsets.zero

        return cell
    }





   override func viewDidLoad() {
    super.viewDidLoad()


    var  i = 0;
    var sum = 0;

    for i in 0...itemName.count
    {
        let title = itemName[i]
        let str : String = title.value(forKey: "ee") as! String
        sum = sum + Int(str)!
    }
    var avg = sum/itemName.count

    print("Score Is", avg)
    }

enter image description here

最佳答案

您可以使用 for 循环对 View did load 方法中的值进行求和

    var  i = 0;
    var sum = 0;

    for i in 0...itemName.count-1
    {
        let title = itemName[i]
        let str :String = title.value(forKey: "ee")
        sum = sum + Int(str)
    }

    var avg = sum/itemName.count

关于ios - 查找表格 View 中所有数字的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54729962/

相关文章:

ios - 为什么 removeAllObservers() 在 deinit 中不起作用?

ios - 运行时与 MPAndroidChart 的用户交互

ios - MessageComposeViewController 仅出现一次

ios - 基于一对多关系的Coredata NSFetchedResultsController谓词(外部)

JavaFX TableView CellValueFactory

ios - 一次获取所有健身数据

ios - 创建数组作为实体的属性

iphone - NSFetchedResultsController 获取请求 - 更新谓词和 UITableView

ios - 将 UISegmentedControl 的结果添加到核心数据实体中的属性

c# - 在 TableView 中绑定(bind) TextCell