A shop takes payments by card, by PayPal and in cash. Every payment has an amount, in cents, and a total: the amount plus a processing fee. The total is worked out the same way for every payment; only the fee depends on the kind of payment. That is what an abstract class is for: it holds the shared part, says that every payment has a fee, and leaves the fee itself to each kind of payment.
- The abstract class
Paymentis built from anamount, in cents, and keeps it. Its methodfee()is abstract: every payment has a fee, butPaymentcan't say what it is. Its methodtotal()is concrete: it returns the amount plusfee(). Card,PayPalandCashinherit fromPayment, keep itstotal()as it is, and each writes its ownfee():
Cardpays 2%: its fee is amount × 2 / 100.PayPalpays 3% plus 30 cents: its fee is amount × 3 / 100 + 30.Cashcosts nothing: its fee is 0.
Swift has no abstract classes. As in the abstract-classes lesson, Payment's own fee() calls fatalError("must override"), and each subclass (: Payment) overrides it. The subclasses inherit init, amount and total. Dividing two Ints drops the fraction.
Every division rounds down: a card payment of 1999 cents has a fee of 39, not 39.98.
The starter code already has every class and every method header: declare the property and write the bodies. For each test, the harness creates the payments in the order given and prints two lines: each payment's total, total(), separated by spaces, and then the sum of all the fees. It calls them through the abstract type Payment, never through Card, PayPal or Cash.
Example 1:
Input:
Card(1999)
PayPal(500)
Cash(700)
Output:
2038 545 700
84
Explanation: The card's fee is 1999 × 2 / 100 = 39 (39.98 rounded down), so its total is 2038. PayPal's fee is 500 × 3 / 100 + 30 = 45, total 545. Cash has no fee: total 700. The fees add up to 39 + 45 + 0 = 84.
Example 2:
Input:
Card(49)
PayPal(33)
Card(50)
Output:
49 63 51
31
Explanation: 49 × 2 / 100 is 0.98, rounded down to 0. PayPal's 33 × 3 / 100 is 0.99, rounded down to 0, plus 30. The second card's 50 × 2 / 100 is exactly 1. The fees are 0 + 30 + 1 = 31.
Example 3:
Input:
Card(0)
PayPal(0)
Cash(0)
Output:
0 30 0
30
Explanation: Amounts can be 0. PayPal still adds its 30 cents.
Constraints:
- Every test has between 1 and 100 payments.
- Every amount is an integer from 0 to 106 cents.
Note:
Every fee and every total takes O(1) time.
Free plan: 30 tutor messages. PRO is unlimited.
