Home > Back-end >  How to write only else condition in Swift?
How to write only else condition in Swift?

Time:11-22

I have some conditional code in which i dont want to show anything in if condition

if let _ = Manager.shared.initiateCheck() {
            
        } else {
            showLoader = true
        }

but its not good to write empty if how to handle this? I tried giving !(Manager.shared.initiateCheck()) but its giving error.

Thank you for help

CodePudding user response:

The if let construct is a shorthand for unwrapping a value so that you can work with it safely. Your use-case is the exact opposite, therefore it is not the right solution.

Use simple null-check instead:

if Manager.shared.initiateCheck() == nil {
    showLoader = true            
}

alternatively, if you need to short-circuit the execution, you can opt for guard let statement:

guard let initiatedCheck = Manager.shared.initiateCheck() else {
    showLoader = true            
    return
}

(note that it depends on the return value of your function, which we don't see here)

  • Related