我有一个类的UITableViewController的:如何查找数组中所有数字的总和?
class foodListTable: UITableViewController
我有9个数值数组它:
var calorieNumberArray = [0,0,0,0,0,0,0,0,0]
(是的,数组中的值做改变。)我想找到数组中所有值的总和。我已经通过创建这种不断的尝试:
let calorieTotal = calorieNumberArray.reduce(0) { $0 + $1 }
我使用的苹果开发者页面在https://developer.apple.com/documentation/swift/array摸不着头脑。每当我使用let calorieTotal = array.reduce(0) { $0 + $1 }
时,出现错误:“'foodListTable.Type'没有名为'calorieNumberArray'的成员'”
我该如何解决这个问题?我需要改变我在数组中添加数字的方式吗?
这里是我的所有此类代码:
class foodListTable: UITableViewController {
var calorieNumberArray = [0,0,0,0,0,0,0,0,0]
let calorieTotal = calorieNumberArray.reduce(0) { $0 + $1 }
var foods = [Food]()
override func viewDidLoad() {
super.viewDidLoad()
self.foods = [Food(Name: "Small French Fries: 197 Cal."),Food(Name: "Cheeseburger: 359 Cal., One Patty"),Food(Name: "Cheese Pizza: 351 Cal., One Slice"),Food(Name: "Fried Chicken Breast: 320 Cal."),Food(Name: "Large Taco: 571 Cal."),Food(Name: "Hotdog: 315 Cal., With Ketchup"),Food(Name: "Tuna Sandwich: 287 Cal."),Food(Name: "1 Cup Vanilla Ice Cream: 290 Cal."),Food(Name: "1 1/2 Cup Vegetable Salad: 30 Cal.")]
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.foods.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
var food : Food
food = foods[indexPath.row]
cell.textLabel.text = food.Name
tableView.deselectRowAtIndexPath(indexPath, animated: true)
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
if cell.accessoryType == .None {
if indexPath.row == 0 {
calorieNumberArray[0] = 197
}
if indexPath.row == 1 {
calorieNumberArray[1] = 359
}
if indexPath.row == 2 {
calorieNumberArray[2] = 351
}
if indexPath.row == 3 {
calorieNumberArray[3] = 320
}
if indexPath.row == 4 {
calorieNumberArray[4] = 571
}
if indexPath.row == 5 {
calorieNumberArray[5] = 315
}
if indexPath.row == 6 {
calorieNumberArray[6] = 287
}
if indexPath.row == 7 {
calorieNumberArray[7] = 290
}
if indexPath.row == 8 {
calorieNumberArray[8] = 30
}
cell.accessoryType = .Checkmark
} else {
if indexPath.row == 0 {
calorieNumberArray[0] = 0
}
if indexPath.row == 1 {
calorieNumberArray[1] = 0
}
if indexPath.row == 2 {
calorieNumberArray[2] = 0
}
if indexPath.row == 3 {
calorieNumberArray[3] = 0
}
if indexPath.row == 4 {
calorieNumberArray[4] = 0
}
if indexPath.row == 5 {
calorieNumberArray[5] = 0
}
if indexPath.row == 6 {
calorieNumberArray[6] = 0
}
if indexPath.row == 7 {
calorieNumberArray[7] = 0
}
if indexPath.row == 8 {
calorieNumberArray[8] = 0
}
cell.accessoryType = .None
}
}
}
注意:类型名称应该大写:'FoodListTable',而不是'foodListTable'。 – 2014-12-06 00:56:52
好的,我会解决这个问题。 – TheCentral 2014-12-06 00:57:45