Reputation: 703
I am trying to do some math with user input numbers I get from UITextFields. The problem, there could be nothing in the TextField, in that case the value should be set to zero. I tried the guard statement but it seems I use it the wrong way:
guard let number = numberTextField.text else{ let number = 0}
What is wrong with this code? What should I change?
Upvotes: 0
Views: 84
Reputation: 107
You'll want to use a default value instead of a guard to get the behavior you desire.
let number = Double(numberTextField.text) ?? 0
Upvotes: 0
Reputation: 17040
The guard
statement cannot be used, because it requires you to exit from the function if the condition is false
. Instead, you should use the ??
operator:
let number = numberTextField.text.flatMap { Int($0) } ?? 0
Why flatMap
? Because we need to convert the String
to an Int
(or a Double
, if this may contain a floating-point value) in order for it to be the same type as the 0
. flatMap
on an optional returns the value inside the closure if text
is not nil
, but returns nil
if it is. In either case you'll end up with an optional Int
, which is then made non-optional by supplying the default value of 0
via the ??
operator.
Upvotes: 4
Reputation: 104
Nothing means empty string rather than nil "guard let" is used to check nil value
Let try the method below
if numberTextField.text.isEmpty {
let number = 0
}
Upvotes: -1