如何检查用户输入的答案是否包含字母,如果是,您如何将答案默认为0?

这是我到目前为止的代码,现在当用户输入任何字母时,我的标签什么都不显示,我想弄清楚的是如何将没有的“”变成0。我尝试在“”上执行if语句label.txt =“是的,但是没有成功。找到我想要的结果的更好的方法是什么?

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var game1: UITextField!
    @IBOutlet weak var game2: UITextField!
    @IBOutlet weak var game3: UITextField!

    @IBOutlet weak var series: UILabel!
    @IBOutlet weak var average: UILabel!
    @IBOutlet weak var high: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

    }

    @IBAction func calculate(_ sender: Any) {
        self.view.endEditing(true)

        guard
                let text1 = game1.text,
                let text2 = game2.text,
                let text3 = game3.text
        else { return }

        guard
                let game1Results = Int(text1),
                let game2Results = Int(text2),
                let game3Results = Int(text3)
        else { return }

        let gameResultsArray = [game1Results, game2Results, game3Results]
        let sumArray = gameResultsArray.reduce(0, +)
        let positiveArray = gameResultsArray.filter {
            (item: Int) -> Bool in return item > 0
        }

        var avgArrayValue = 0

        if positiveArray.count == 0
        {
            avgArrayValue = 0
        }else {
            avgArrayValue = sumArray / positiveArray.count
        }

        series.text = "\(sumArray)"
        average.text = "\(avgArrayValue)"
        if let maximumVal = gameResultsArray.max() {
        high.text = String(maximumVal)
        }
    }
}
评论
  • 纯情小火鸡
    纯情小火鸡 回复

    Here is what you need, convert String to Int and give the default 0. Instead of using the guard let return use this method:

    代替这个:

    guard let game1Results = Int(text1) else { return }
    

    用这个:

    let game1Results = Int(text1) ?? 0