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
CodePudding user response:
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
extension String {
var isNumber: Bool {
return Double(self) != nil
}
}
Then combine to your condition
if text == nil || (text!.isNumber && Float(text!)! > 0) {
print("i am in")
}
The result will be like this
let text: String? = "2.0" // i am in
let text: String? = nil // i am in
let text: String? = "-1.0" // nothing print
CodePudding user response:
text is an optional
if (text == nil) || Float(text ?? "") ?? 0 > 0 {
print("i am in")
}
CodePudding user response:
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:
let text: String? = nil
if let textString = text, let number = Float(textString) {
if number > 0 {
print("I am in")
}
else {
print("I am out")
}
}
else {
print("I am in")
}
CodePudding user response:
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
.if text == nil || Float(text!) ?? 0 > 0 { print("i am in") }