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!