1

I am setting a variable to the doubleValue of a UITextField with the following,

let enteredTargetDays : Double = numberFormatter.number(from: textField2.text!)?.doubleValue ?? 0.00

This ensures that even if the textField2.text is nil and a doubleValue cannot be extrapolated, 0.00 will return. But what if I don't want a default value, and just want the function to return if the textField2.text is nil?

Is the only way to do this to first check textField2.text for nil before setting the variable, or is there is a quicker, one-liner, Swifty way to do it?

user13138159
  • 172
  • 9

1 Answers1

1

Not wanting to use a default value and just wanting the function to return is exactly what guard statements are for:

func yourFunction() {
    guard let enteredTargetDays = numberFormatter.number(from: textField2.text ?? "")?.doubleValue else {
        return
    }

    // do something with `enteredTargetDays` here
}
TylerP
  • 9,600
  • 4
  • 39
  • 43
  • Just a follow up question: it would make sense to also use textField2.text! instead of providing a default value for that if I wanted to strictly based off what was present, and that would be acceptable? – user13138159 Apr 04 '20 at 22:25
  • Hmm, I'm not quite sure I understand your follow-up question. – TylerP Apr 04 '20 at 22:27
  • So, in your answer, you have textField2.text ?? "", but I could use textField2.text! instead and if textField2.text was nil the guard would still catch it and return? – user13138159 Apr 04 '20 at 22:29
  • Oh, sure you could use `textField2.text!` since the `text` property of `UITextField` is [pretty much guaranteed to never be nil](https://stackoverflow.com/questions/42861115/why-is-uitextfield-text-an-optional). I just personally hate using the force-unwrap operator in all cases so I opted to use the nil-coalescing operator (aka `??`) there instead. And yes even if the textfield's text was empty/nil, the guard will still catch this because the `numberFormatter` will return nil from the call to `number(from:)` (because you can't really make a number from an empty string). – TylerP Apr 04 '20 at 22:40
  • 1
    Ah, that makes sense! Thank you for explaining that. I actually quickly realized this because when I started using guard, I had to check for an empty string instead of nil. Makes sense. – user13138159 Apr 04 '20 at 22:47