I am not sure how to call this scenario. Say i have this variable
let text: String?
How can it be coded such that my if condition would be something like this:
if (text == nil || Float(text) > 0) {
print("i am in")
}
I keep getting No exact matches in call to initializer
4
Answers
Two additional things must be done:
After your check if
text
isnil
you must still unwrap the optionaltext
to use it with theFloat()
constructor. Here I’ve used a forced unwrap!
which in general is dangerous, but we know at this pointtext
cannot benil
due to the first test. Iftext
isnil
, the||
uses short-circuit evaluation to return true without executing the right side.Next,
Float(text!)
returns aFloat?
because that text might not convert to a validFloat
. In order to unwrap that I’ve used the nil-coalescing operator??
to unwrap theFloat
value or use0
if the value isnil
.First of all, looks like you want to check if text != nil then if text is number check if text > 0
Because in here you have optional String so you should have a specific to check if string text not nil. Then check if it is number.
Code will be like this
Then combine to your condition
The result will be like this
text is an optional
You have two issues here:
text is a
String?
and therefore it needs to be unwrapped to pass it toFloat()
Float()
returns an optional, this also should be unwrapped to be used with the>
operator.I would avoid force unwrapping, you can do something like: