Tony Merritt Tony Merritt - 1 year ago 55
Swift Question

Don't call function if argument is not a number

I am new to programming. I've been following tutorials to learn Swift.

I have finished an app by following a tutorial but both the tutor's app and mine have an error.

This basic app adds a number to itself. It works great for the most part and is finished. However, when I entered a character instead of a number, it crashed. How can I check the value is a number before it runs the function?

Here is the code:

@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

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.

I thought maybe I could just add in &&
whatTxt.text != Int
, but that didn't work, and I think i have the wrong idea of what Int may be in that case.

Answer Source

Don't force unwrap. You can use nil coalescing with the default values (probably "" and 0):

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

You can't check if it's not a number before running the function (the action will always be triggered) however if you really want to avoid the code from running just unwrap the value in a guard:

@IBAction func onPlayBtn(sender: UIButton) {

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

    // The rest of the code goes here, no if necessary

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