数据模型:
import Foundation
class CartItem {
var mealSize: MealSize
var qty: Int
var pName: String
init(mealSize: MealSize, qty: Int, pName: String){
self.mealSize = mealSize
self.qty = qty
self.pName = pName
}
}
class Cart {
static let currentCart = Cart()
var restaruant: Restaruant?
var items = [CartItem]()
var address: String?
var name: Meal?
func getTotal() -> Float {
var total: Float = 0
for item in self.items {
total = total + Float(item.qty) * item.mealSize.price!
}
return total
}
func reset() {
self.restaruant = nil
self.items = []
self.address = nil
self.name = nil
}
}

用餐VC,以便用户点击将商品添加到购物车。
class ProductDetailViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
var meal: Meal?
var restaurant: Restaurant?
var mealSize = [MealSize]()
var mealSizes: MealSize?
var pName: String = ""
var qty = 1
var ps: String = ""
// Picker Information.
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return mealSize.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
let item = self.mealSize[row]
mealSize = item
priceLbl.text = "$"+"\((item.price)!)"
//PS Product Size. Used to reference the size id.
ms = "\((item.price)!)"
print("\((item.price)!)")
return "\((item.sizeString)!)"
}
@IBAction func addTo(_ sender: Any) {
let cartItem = CartItem(mealSize: self.mealSizes!, qty: self.qty, pName: self.pName)
guard let cartRestaurant = Cart.currentCart.restaurant, let currentRestaurant = self.restaurant else {
//If requirements are not met
Cart.currentCart.restaurant = self.restaurant
Cart.currentCart.items.append(cartItem)
return
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "cartInfo" {
let controller = segue.destination as! CartController
controller.meal = meal
}
}

然后我将我的用户转移到购物车页面以添加项目,从这里,我需要用户可以选择返回并编辑他们的购物车。
import UIKit
import MapKit
import CoreLocation
class CartClass: UIViewController
var meal: Meal!
var mealSizes: MealSize!
//Populate products in cart.
extension CartController: UITabBarDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Cart.currentCart.items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "shoppingCartCell", for: indexPath) as! CartCell
let cart = Cart.currentCart.items[indexPath.row]
let cartTotal = cart.mealSize.price! * Float(cart.qty)
let name = cart.mealSize.sizeString! + "(s)" + " of " + cart.pName
cell.lblQty.text = "\(cart.qty)"
cell.lblTotal.text = "$" + String(format: "%.02f", cartTotal)
cell.lblName.text = name
return cell
}

我已将所有商品添加到购物车中并完美打印出来。我创建了一个按钮,用于从购物车中删除商品,但是,我没有选项来编辑各个选项。我将如何使用此代码执行此操作?