Start learning free

LESSON 611 OF 640 · OBJECT-ORIENTED PROGRAMMING

Printable Things in Swift

Practice

You write an interface and two classes that use it.

Printable is an interface with one method, label(). It returns a short text about the item.

Two classes implement it:

  • Book(title, author). Its label is the title, then by, then the author.
  • Ticket(code). Its label is Ticket, then the code.

One space separates the words of a label.

In Swift, Printable is a protocol. Book and Ticket adopt it.

Then write printAll(items). It goes in the class Solution. It returns every item's label, in the same order.

The items mix books and tickets. Use each one only through label().

The starter code already has the classes and their constructors. The harness prints each label on its own line.

 

Example 1:

Input: Book("Dune", "Herbert"), Ticket("A12")
Output:
Dune by Herbert
Ticket A12

Explanation: The book joins its title and author with by.
The ticket puts Ticket before its code.

Example 2:

Input: Ticket("B7"), Ticket("C3"), Book("Emma", "Austen")
Output:
Ticket B7
Ticket C3
Emma by Austen

Explanation: The labels keep the order of the items.

Example 3:

Input: Book("1984", "Orwell")
Output:
1984 by Orwell

Explanation: A title can be digits. It is still text.

 

Constraints:

  • 1 to 100 items.
  • Each title, author and code is one word.
  • A word has 1 to 20 letters or digits.
STEP 1 OF 6
    Ctrl + Enter to check

    Printable Things 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