Home > Enterprise >  Using an if condition for a variable? in Swift 5
Using an if condition for a variable? in Swift 5

Time:09-05

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:

  1. text is a String? and therefore it needs to be unwrapped to pass it to Float()

  2. 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:

  1. After your check if text is nil you must still unwrap the optional text to use it with the Float() constructor. Here I’ve used a forced unwrap ! which in general is dangerous, but we know at this point text cannot be nil due to the first test. If text is nil, the || uses short-circuit evaluation to return true without executing the right side.

  2. Next, Float(text!) returns a Float? because that text might not convert to a valid Float. In order to unwrap that I’ve used the nil-coalescing operator ?? to unwrap the Float value or use 0 if the value is nil.

    if text == nil || Float(text!) ?? 0 > 0 {
        print("i am in")
    }
    
  • Related