0
votes

following code in func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) causing this error:Command failed due to signal: Segmentation fault: 11 cause

var finalStr = (textField.text! as NSString).replacingCharacters(in: range, with: string) 
if textfield == mobile && finalStr.hasPrefix("0"){ 
textField.text = finalStr.nonZeroNumber 
return false }

var nonZeroNumber:String{
             let local = Double(self)
            return String(format: "%.0f",local!)
 }

what's wrong with the code, as its working fine in the sample project.

1

1 Answers

0
votes

You're force unwrapping local without checking if it's nil, which it may be if you have non-numeric characters.

You either need a default value, or change the method to return nil on failure and and check for nil elsewhere.

var nonZeroNumber:String{
    let local = Double(self) ?? 0       // use 0 if Double(self) was nil
    return String(format: "%.0f",local) // local, not local!
}

or

var nonZeroNumber: String? {    // note Optional
    guard let local = Double(self) else {
        return nil
    }
    return String(format: "%.0f, local) 
}

... 
textField.text = finalStr.nonZeroNumber ?? "default value"