Build a Wine Rack

Published by Colin Brash in

Create a WineRack with the following properties:

  • Has a default initializer that creates a WineRack with a specified width and height.
  • Has a failable initializer that creates a WineRack with a specified width and height, filled with specified wines. Wines fill the rack from top left. If there are too many wines for the size of the rack, the initializer fails.
  • When a WineRack object is printed, it displays a graphical representation of the rack, using the unicode symbol for an empty slot, and for a slot filled with wine.
  • Returns the wine at a given rack location using a subscript (e.g. wineRack[(0,0)]).

Examples

print(WineRack(height: 2, width: 3)) ➞
○○○
○○○

print(WineRack(height: 2, width: 3, wines: ["Riesling", "Syrah", "Riesling", "Syrah", "Syrah"])!) ➞
●●●
●●○

WineRack(height: 1, width: 1, wines: ["Riesling", "Syrah"]) ➞ nil

WineRack(height: 2, width: 3, wines: ["Riesling", "Syrah", "Riesling", "Syrah", "Syrah"])?[(0, 0)] ➞ "Riesling"

WineRack(height: 2, width: 3, wines: ["Riesling", "Syrah", "Riesling", "Syrah", "Syrah"])?[(1, 1)] ➞ "Syrah"

WineRack(height: 2, width: 3, wines: ["Riesling", "Syrah", "Riesling", "Syrah", "Syrah"])?[(1, 2)] ➞ nil

Notes

  • Locations in a WineRack that do not contain a wine should return nil.
  • Locations are represented by a tuple with 2 values: (row, column).
  • When printing a WineRack rows should be separated by new lines (\n)
Watch a quick demo on how Edabit works.