如果参数不是数字,请不要调用函数

时间:2016-08-05 13:28:52

标签: swift int

我是编程新手。我一直在学习Swift。

我已经按照教程完成了一个应用程序,但导师的应用程序和我的应用程序都有错误。

这个基本的应用程序为自己添加了一个数字。它在大多数情况下都很有效并且已经完成。但是,当我输入一个字符而不是一个数字时,它就崩溃了。如何在运行函数之前检查值是否为数字?

以下是代码:

@IBAction func onPlayBtn(sender: UIButton) {


    if whatTxt.text != nil && whatTxt.text != ""{

        playBtn.hidden = true
        logo.hidden = true
        whatTxt.hidden = true

        sumBtn.hidden = false
        sumTxt.hidden = false

        resetLbl()
        maxTimes = Int(whatTxt.text!)!
        currentTimes = 0

       here is the line of code I know is checking that the box is not empty, it doesn't run the function if it is empty.

我想也许我可以加入&& whatTxt.text != Int,但这不起作用,而且我认为在这种情况下我可能错误地认识到Int。

4 个答案:

答案 0 :(得分:2)

不要强行打开包装。您可以使用nil合并默认值(可能是""0):

maxTimes = Int(whatTxt.text ?? "") ?? 0

在运行该函数之前,您无法检查它是否不是数字(操作将始终被触发)但是如果您真的想要避免代码运行,只需打开{中的值{1}}:

guard

答案 1 :(得分:1)

一种方法是使用NSCharacterSet和rangeOfCharacterFromSet来理解字符串是否包含数字:

var textFieldValue = "HELLO" // This should be the value from your textfield
let decimalCharacters = NSCharacterSet.decimalDigitCharacterSet()
let rangeResult = textFieldValue.rangeOfCharacterFromSet(decimalCharacters, options: NSStringCompareOptions(), range: nil)

if rangeResult != nil {
    // Contain numbers
} else {
    // Not contain numbers
}

另一种方法是使用Regex模式。

答案 2 :(得分:1)

崩溃发生在maxTimes = Int(whatTxt.text!)!Int()初始值设定项返回Int?Optional<Int>),表示StringInt转换失败(正如您所遇到的那样)。当初始值设定项返回nil时会发生崩溃,但您仍尝试使用!强制解包它。

相反,请安全地打开它:

@IBAction func onPlayBtn(sender: UIButton) {


    if let text = whatTxt.text where !text.isEmpty { //see note below

        playBtn.hidden = true
        logo.hidden = true
        whatTxt.hidden = true

        sumBtn.hidden = false
        sumTxt.hidden = false

        resetLbl()

        if let maxTimes = Int(text) {
            //text represents a valid Int, now available as the Int "maxTimes"
        }
        else {
            //text does not represent a valid Int
        }

        currentTimes = 0

注意:请勿检查nilwhatTxt.text != nil),然后强制解包(whatTxt.text!)。相反,使用if let绑定来安全地解包:if let text = whatTxt.text

作为旁注,请尽量避免使用lblbtntxt等名称。 labelbuttontext的时间不会太长,而且它会使您的代码看起来像是由t3x + sp3 @ k中的前卫少年编写的

答案 3 :(得分:-2)

谢谢所有这个答案,在输入信件时没有进入数学屏幕就解决了这个问题。谢谢你转到jpg1503

@IBAction func onPlayBtn(发件人:UIButton){

guard let whatText = whatTxt.text, _ = Int(whatText) else { return }



    if whatTxt.text != nil && whatTxt.text != ""{


        playBtn.hidden = true
        logo.hidden = true
        whatTxt.hidden = true

        sumBtn.hidden = false
        sumTxt.hidden = false

        resetLbl()
        maxTimes = Int(whatTxt.text ?? "") ?? 0
        currentTimes = 0
相关问题