The goal of today's module project is to create a Currency Conversion playground that can convert from US dollars (USD) to Canadian dollars (CAD) and Mexican Pesos (MXN).
Get the currency conversion value from Google:
On August 7th, 2019 they were:
$1 USD to $1.33 CAD
$1 USD to $19.70 MXN
Create a new playground in this repository called "CurrencyConverter"
-
Create a currency type enum below the
import
statements.enum Currency { case cad case mxn }
-
Create a constant called
usToCad
and set its value to the current conversion value (googlingusd to cad
should give you the value). Do the same for a new constant calledusToMxn
. -
Create a property named
currency
of typeCurrency
. This will store the current currency type we'll be converting to. Set an initial value of.cad
. -
Create a helper method to calculate the currency based on the Currency using the method signature:
func convert(_ dollars: Double) -> Double { }
-
In the above method:
- Check the value of
currency
to see whether you should convert to CAD or MXN - Perform the conversion with the dollars passed into this method
- Return the converted value
- Check the value of
-
Create a function called
convert(amountString: String) -> String?
In it, do the following:- create a constant called
amount
. Its value should be theamountString
that is initialized into aDouble
- use a
guard let
to unwrap the newamount
constant. - convert the dollar amount to the expected currency (hint, you'll want to call the
convert
method you created in step 4
- create a constant called
-
Test your code by calling
convert(amountString
with some values. Change yourcurrency
to both.cad
and.mxn
(by manually changing the value of yourcurrency
variable above) to make sure the conversion works for both currencies.
-
Customize the output using a
NumberFormatter
var currencyFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .currency return formatter }()
-
Use the
string(from:)
method to convert from a number to a String for display