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 above the class and below the
import
statements.enum Currency { case cad case mxn }
-
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)
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 3) - Update the
toCurrencyTextField.text
property with the converted currency value
- create a constant called
-
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