我有一個類的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