Checking for NIL

I have a program where the user enters 2 fields with numerics. If they accidently enter a letter the program crashes. How can I check for NIL without making the variable optional. If I make it optional I get an error in the Textfield. How can I test a Textfield for NIL? Please help.

You can filter what is typed, with TextField delegate. Don't forget to declare the ViewController as the delegate for the TextFields.

Can be improved if you want to allow to move insertion cursor in an existing text..

let gcTabAscii = 9   
let gcLineFeedAscii = 10   
let gcReturnAscii = 13   

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        guard let charCode = string.first?.asciiValue else {
            if string == "" {   // Accept backspace
                return true
            }
            return false
        }

        if charCode == gcLineFeedAscii || charCode == gcReturnAscii {   // It is lineFeed even when typing return
            return true
        }
        if charCode == gcTabAscii {   //  Tab
            textField.text = textField.text!
            return false // You should fine tune here to allow for - sign or dot sign at start
        }
        
        let newString = textField.text! + string

        if Int(newString) != nil {  // So we typed something in newString and it is a valid number ; if you do not expect an Int but any number, test for Float(newString)
            return true
        } else {
            return false  // You could allow for - or starting dot with 
            // return newString == "-" || newString == "."
        }
    }

Thank you very much. I should've told you I'm a beginner. Where does that go? Right now all I have is this:
@State private var cost = "" TextField("Cost", text: $cost) .frame(width: 75, height: 25) .padding(20) .fontWeight(.bold) .font(.system(size: 22)) .foregroundColor(.white) .background(Color.brown) .cornerRadius(025) Thanks again.

How do I call the func? Please help. Thank you.

Thanks for your help.

Checking for NIL
 
 
Q