Joshua Abrams Joshua Abrams - 3 years ago 108
Swift Question

If variable is equal to a number else error code

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")
// }

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download