Introduction to the Shopping Cart Module

Welcome to your third unit for this course dedicated to practicing Test Driven Development (TDD) utilizing Swift and XCTest. We're going to start building a new system; this time, we'll create a ShoppingCart class with multiple features.

This course emphasizes hands-on practice, where you'll receive requirements through tests, one at a time. Your task is to write tests AND implement code that makes each test pass, simulating a real-world TDD environment. Previously, tests were provided for you, but this time, it's all up to you! Start by asserting what the output should be, even if the method or property doesn’t exist yet. This mimics real-world workflows, where features are often discussed and validated via tests before any implementation begins. Think in terms of: What do I expect this function to return or do?

Remember to use the core concepts of the Red-Green-Refactor cycle while completing these coding exercises. I'm still here to help! Just ask if you encounter issues.

Requirements for `ShoppingCart` Class
1. Starting with an Empty Cart
2. Adding a Single Item
  • Description: Verify that when a single item is added to the cart, the cart's item count increases, and the total price reflects the added item's price.
  • Details
    • Use the addItem(item:) method to add an item to the cart.
    • Confirm that getItemCount() returns the correct number of items after an item is added.
    • Ensure getTotal() accurately calculates and returns the total price of items in the cart.
  • Examples: Adding an item ("1", "Book", 10) should result in an item count of 1 and a total cost of 10.
Swift
extension ShoppingCart {
    func addItem(id: String, name: String, price: Double, quantity: Int = 1) {
        if let existingItem = items[id] {
            items[id] = (name, price, existingItem.quantity + quantity)
        } else {
            items[id] = (name, price, quantity)
        }
    }
}

extension ShoppingCartTests {
    func testAddSingleItem() {
        let cart = ShoppingCart()
        cart.addItem(id: "1", name: "Book", price: 10.0)
        XCTAssertEqual(cart.getItemCount(), 1)
        XCTAssertEqual(cart.getTotal(), 10.0)
    }
}
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal