-2

So essentially I'm creating a calculator type app, in which I only want to intake numbers, decimals, and the negative sign. I'm fairly new to Xcode and swift so I wouldn't consider my knowledge extensive when it comes to knowing how to handle these sorts of issues.

Here is my current attempt at a solution

 let v = Double(inputOne.text!)!

(inputOne. is the associated text field)

This works well in my algorithm when everything is inputted as it should be, however when inputting anything other than a valid double I receive "Fatal error: Unexpectedly found nil while unwrapping an Optional value", and the app crashes.

I figured someone may have already come up with a creative solution to this problem or that there may be some command in Xcode that limits text fields in this way, however I am new to Xcode and unaware of such things if they exist. Maybe there is some way I can implement an error message that occurs whenever something other than a valid double is inputted without crashing the app? Any creative solutions would be appreciated.

Alex
  • 1
  • 2
  • Does this answer your question? [What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Magnas May 23 '20 at 02:31

1 Answers1

0

You can use a UITextView as your input field (if you want a one-line input, use a textField). Then, simply set your ViewController as the textView's delegate -inside your ViewController add the following line (and don't forget to inherit UITextViewDelegate):

textView.delegate = self

Essentially, what this does is allow the ViewController to take ownership of some of the textView's functionalities. In this case, we are interested in filtering the user input and for that you can use the following function:

/// Intercept whatever character the user is typing on the keyboard
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    // If the user presses "enter", handle it the way you want
    guard text.rangeOfCharacter(from: CharacterSet.newlines) == nil else {
        // Handle new line
    }
    // If character is a digit, a dot, or a dash, allow input, else reject it.
    if text == "-" || text.rangeOfCharacter(from: CharacterSet.decimalDigits) != nil || text == "." {
        return true
    } else {
        return false
    }
}
rs7
  • 1,618
  • 1
  • 8
  • 16