如果变量等于其他错误代码

时间:2016-10-20 21:16:22

标签: swift if-statement swift3

if语句,用于确定用户是否输入了可以使用的变量,如果没有输出错误消息

当用户通过enterMoneyAmount输入字符时,如果它是一个完成代码的数字,如果不是数字打印错误消息到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")
    // }
 }

2 个答案:

答案 0 :(得分:0)

你可以试试这个:

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

您还可以将文本字段的键盘类型设置为数字/小数点,以防止用户输入任何其他内容。

答案 1 :(得分: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")
  }