Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. @IBAction func addToCart(_ sender: UIBarButtonItem) {
  2. let itemToAdd = product
  3. let existingIndex = cart.containsAtIndex(product!)
  4. // If item from catalogue exist in cart, then modify
  5. if (existingIndex >= 0) {
  6. cart.changeItem(existingIndex, newItem: itemToAdd!)
  7. modifyCart(product: itemToAdd!)
  8. }
  9. // If item is not found in cart, then add a new one
  10. else {
  11. let storyboard = UIStoryboard(name: "Main", bundle: nil)
  12. if let controller = storyboard.instantiateViewController(withIdentifier: "CartTableView") as? CartTableViewController {
  13. let newIndexPath = IndexPath(row: cart.numberOfItems(), section: 0)
  14. cart.addItem(itemToAdd!)
  15. controller.tableView.insertRows(at: [newIndexPath], with: .automatic)
  16. saveToCart(product: itemToAdd!, update: true)
  17. }
  18. }
  19. self.navigationController?.popViewController(animated: true)
  20. self.dismiss(animated: true, completion: nil)
  21. }
  22.  
  23.  
  24.  
  25. private func saveToCart(product: Product, update: Bool) {
  26. let realm = try! Realm()
  27. print(product)
  28. try! realm.write {
  29. realm.add(product, update: true)
  30. }
  31. }
  32.  
  33. private func modifyCart(product: Product) {
  34. let prodName = product.itemName
  35. let realm = try! Realm()
  36. try! realm.write {
  37. let item = realm.objects(Product.self).filter("itemName = %@", prodName).first
  38. item!.quantity = product.quantity
  39. }
  40. }
  41.  
  42. class Cart: NSObject {
  43.  
  44.  
  45. static let myCart = Cart()
  46. private var products: [Product]
  47.  
  48. private override init() {
  49. self.products = []
  50. }
  51.  
  52. func getCartItems() -> [Product] {
  53. return products
  54. }
  55.  
  56. func getItem(_ index: Int) -> Product? {
  57. if products.indices.contains(index) {
  58. return products[index]
  59. } else {
  60. return nil
  61. }
  62. }
  63.  
  64. func addItem(_ item: Product) {
  65. products.append(item)
  66. }
  67.  
  68. func removeItem(_ index: Int) {
  69. products.remove(at: index)
  70. }
  71.  
  72. func numberOfItems() -> Int {
  73. return products.count
  74. }
  75.  
  76. func changeItem(_ index: Int, newItem: Product) {
  77. if products.indices.contains(index) {
  78. products[index] = newItem
  79. }
  80. }
  81.  
  82. func containsAtIndex(_ item: Product) -> Int {
  83. for i in (0..<products.count) {
  84. if (products[i].itemName == item.itemName) {
  85. return i
  86. }
  87. }
  88. return -1
  89. }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement