Start learning free

LESSON 619 OF 640 · OBJECT-ORIENTED PROGRAMMING - CHALLENGES

Product Price in Swift

Practice O(1)

Build a Product class for a shop. A product has a name, a price and a discount.

The price is in cents, and it can never go below 0. The discount is a percent from 0 to 100. The setters keep both rules.

Implement the class Product:

  • Product(name, price) creates a product. Its discount starts at 0.
  • price is a property. Reading it gives the price.
  • Setting price to a negative number changes nothing. The old price stays.
  • discount is a property too. Reading it gives the discount.
  • Setting discount below 0 makes it 0. Setting it above 100 makes it 100.
  • finalPrice() returns the price with the discount taken off. It rounds down to a whole cent.

The properties price and discount are stored properties. Each one checks its new value in a didSet block.

Each test case makes one product. Then it runs a list of operations on it, in order.

The output has one line per test case. It shows the name and a colon. Then it lists what each read gives, separated by spaces.

 

Example 1:

Input:
    p = Product("Pen", 250)
    p.price
    p.discount = 10
    p.finalPrice()
    p.price = -40
    p.price
Output: Pen: 250 225 250
Explanation: 10% of 250 cents is 25 cents, so the pen costs 225.
The price can't be -40, so it stays 250.

Example 2:

Input:
    p = Product("Lamp", 999)
    p.discount = 150
    p.discount
    p.finalPrice()
    p.discount = -20
    p.discount
Output: Lamp: 100 0 0
Explanation: 150 is above 100, so the discount becomes 100.
With 100% off, the lamp costs 0.
Then -20 is below 0, so the discount becomes 0.

Example 3:

Input:
    p = Product("Mug", 999)
    p.discount = 15
    p.finalPrice()
    p.price = 0
    p.finalPrice()
Output: Mug: 849 0
Explanation: 15% off 999 cents leaves 849.15 cents.
Rounded down, that is 849.
A price of 0 is allowed. It stays 0 after any discount.

 

Constraints:

  • The first price is a whole number from 0 to 10,000,000.
  • A new price is from -10,000,000 to 10,000,000.
  • A new discount is from -1,000 to 1,000.
  • A name is one word of letters.
  • 1 to 1,000 operations per test case.
  • Each test case reads at least one value.
STEP 1 OF 5
    Ctrl + Enter to check

    Product Price in Swift

    Keep going with Swift500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free