-2

An if statement to determine if a user entered variable that can be used and if not output an error message

When the user enters characters through enterMoneyAmount if it's a number complete the code, if not a number print error message to moneyResults

import UIKit

class ViewController: UIViewController {


var fee: Double = Double(1.20)
var tax: Double = Double(1.07)
var deposit: Double = Double(100)
// set values needed for the calculator to function

@IBOutlet weak var moneyResults: UILabel! //The resulting text applied once the button is pressed

@IBOutlet weak var enterMoneyAmount: UITextField! // Input from the users keyboard

@IBAction func buttonPressed(_ sender: AnyObject) {



    let enteredAmountString = enterMoneyAmount?.text ?? ""
    let enteredAmount: Double = Double(enteredAmountString) ?? 0

    //if enteredAmount: Double == Double("") {

    let mDeposit = enteredAmount - deposit
    let mDepositAndFee = mDeposit / fee
    let mDepositAndFeeAndTax = mDepositAndFee / tax
    moneyResults.text = "$ " + String(mDepositAndFeeAndTax)

    // } else {
   // moneyResults.text = String("Please enter a valid whole number")
    // }
 }
Pranav Wadhwa
  • 7,666
  • 6
  • 39
  • 61

2 Answers2

0

You can try this:

guard let enteredAmount = Double(enteredAmountString) else {
    moneyResults.text = "You did not enter a number."
}

You can also put the textfield's keyboard type to number/decimal pad to prevent the user putting in anything else.

Pranav Wadhwa
  • 7,666
  • 6
  • 39
  • 61
0
if
    let enteredAmountString = enterMoneyAmount.text,
    let enteredAmount = Double(enteredAmountString)
  {
    let mDeposit = enteredAmount - deposit
    let mDepositAndFee = mDeposit / fee
    let mDepositAndFeeAndTax = mDepositAndFee / tax
    moneyResults.text = "$ \(mDepositAndFeeAndTax)"
  }
  else
  {
    moneyResults.text = String("Please enter a valid whole number")
  }
HenryRootTwo
  • 2,572
  • 1
  • 27
  • 27