Fix the safe price parser in a checkout cell

Review the AI's codeEasy10 minApple style

Your task

An AI wrote a Swift checkout cell that reads a price from an API response with three force unwraps: as! Int and two !. It passed a manual test, then crashed in production whenever a field was missing, null or of a different type. The fix reads the response safely and shows "unavailable" instead of crashing.

An assistant wrote display_price(field_lines, supported_currencies). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • field_lines: the response's fields, each written key=value. The two that matter are amount_cents and currency.
  • supported_currencies: the currency codes the formatter can show.
  • Return the display text, or unavailable.

Rules the tests check:

  • Split a line at its first = into a key and a value. Skip lines with no =. If a key appears more than once, use its first line. A missing key has an empty value.
  • The amount is valid when it is one or more digits from 0 to 9, optionally followed by a . and one or more zeros. A JSON number often arrives as a double, so 1299.0 means 1299 cents. Anything else is invalid, including an empty value, null, a minus sign, or a fraction that is not zero.
  • Return unavailable if the currency is empty, the amount is invalid, or the currency is not exactly one of supported_currencies, case included.
  • Otherwise return the currency, a space, the whole units (cents divided by 100, rounded down), a ., and the remaining cents as two digits.

Examples

display_price(field_lines: list[str], supported_currencies: list[str]) -> str
Example 1
Inputdisplay_price(["amount_cents=1299", "currency=USD"], ["USD", "EUR"])
Output"USD 12.99"
Example 2
Inputdisplay_price(["currency=USD"], ["USD", "EUR"])
Output"unavailable"
Example 3
Inputdisplay_price(["amount_cents=5", "currency=EUR"], ["USD", "EUR"])
Output"EUR 0.05"