0

I have 2 textFields where the user enters the latitude and longitude. I have restricted allowed characters to be digits (0-9), dots and dashes, with the code below:

let allowedCharacters = "0123456789-."
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
     let cs = NSCharacterSet(charactersIn: allowedCharacters).inverted
     let filtered = string.components(separatedBy: cs).joined(separator: "")
     return (string == filtered)
    }

The problem I'm facing is, what if the user enters just a dash, or dots only. I tried checking if the text entered is Double, but the app crashes.

let latText = Double(latitudeTextField.text!)
let lngText = Double(longitudeTextField.text!)

if latText != Double(latText!) || lngText != Double(lngText!) {
errorAlert(title: "", message: "Invalid coordinates")
}

Any help would be appreciated!

RochNoure
  • 77
  • 1
  • 6
  • Post your error – vp2698 Apr 04 '18 at 06:19
  • Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value – RochNoure Apr 04 '18 at 06:25
  • I want to stop the code from being executed if the coordinates entered are invalid. – RochNoure Apr 04 '18 at 06:26
  • You should read about optionals and how to handle them safely in the Swift book or in the referenced Q&A. If the input is not a valid double then `latText` is `nil` and the forced unwrapping `latText!` causes the crash. You (almost) never should use the force-unwrap operator `!` – Martin R Apr 04 '18 at 06:31
  • I thought about it but I did not handle it as I should. Thank you for the reminder. I will read more about it. – RochNoure Apr 04 '18 at 06:36
  • 1
    why don't you use regular expression for latitude and longitude. This one will strictly match latitude and longitude values that fall within the correct range: ^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$ – Aleem Apr 04 '18 at 06:38
  • I use this https://pastebin.com/MbZJYWCu function, to check if an object is valid. It returns a True if it is a valid object, you could remove all others except double to make it cleaner. – Egghead Apr 04 '18 at 07:51
  • I will check them out, thank you all! – RochNoure Apr 05 '18 at 04:25

0 Answers0