下面的代码列出了表格视图中的数字。我要做的就是在视图加载功能中打印数字的平均值。 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)
}
答案 0 :(得分:0)
您可以使用for循环对视图加载方法中的值求和
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