-1

I need to figure out a solution to prevent the app from crashing when a value is not entered in a textfield. The idea is if the textfield is empty (nil), the value of that textfield will then equal zero. Below I have copied my code:

let taxPercentDou:Double = Double(taxnosign2!)!

Anyone has any suggestions?

crapio99
  • 21
  • 4
  • Take textfields optional - @IBOutlet car hourlyRate : UITextField? – Chaman Sharma Dec 04 '19 at 02:06
  • you can also check condition for empty text in textfields like --- textfield.text?.trimmingCharacters(in: .whitespaces).isEmpty == true – iVJ Dec 04 '19 at 07:05

2 Answers2

0

You need to stop force unwrapping optionals with the exclamation ! sign:

let b:Double  = Double(rent.text!)!// Rent

If rent.text is nil or contains non-numeric text, your app will crash.

You can check for nil and replace it with "0" using the null coalescing operator:

rent.text ?? "0"

You can pass that into the Double initializer like this:

Double(rent.text ?? "0")

However, this will return nil if rent.text contains non-numeric text. You can use the null coalescing operator again to handle this:

let b: Double = Double(rent.text ?? "0") ?? 0.0 

You could take this one step farther and write a simple utility method to make it easier to use for all your fields:

func convertToDouble(text: String?) -> Double {
    return Double(text ?? "0") ?? 0.0
}

And call it like this:

let b = convertToDouble(rent.text)
Mike Taverne
  • 9,156
  • 2
  • 42
  • 58
  • Thank you so much Mike! I will try it out and I will let you know if it works! Thanks again you don't know how much time you saved me lol – crapio99 Dec 04 '19 at 04:14
0

Please find the below code. It Might Help you.

static func isNull(aString: AnyObject?) -> Bool
{
    //Check for null
    if(aString is NSNull){
        return true
    }

    if(aString == nil){
        return true
    }

    let x: AnyObject? = aString

    //if string is nsnumber , convert it into string and check
    if(aString is NSNumber){
        var aString1 : String? = ""
        aString1 = String(describing: aString)
        return self.isStringEmpty(aString: aString1!)
    }

    if let aString1 = x as? String
    {
        return self.isStringEmpty(aString: aString1)
    }
    else
    {
        return true
    }

}