Search code examples
swiftif-statementoption-type

How to do optional with an or conditions in Swift?


i am trying to do following:-

var isSomeThingTrue = checkSomeThing()

if (let someOptional = getSomeOptional(),
   let anotherOptional = getAnotherOptional(withSomeOptional: someOptional)) ||
   isSomeThingTrue {
   // do something
} else {
   // do something else
}

Is there a way this could be achieved with if statement or i have to use a guard statement ?


Solution

  • I guess there are many ways to skin this cat so here is one more, if you move the code to be executed inside the if into a function to avoid code duplication the below way is in my opinion easy to read

    if let someOptional = getSomeOptional(), let anotherOptional = getAnotherOptional(withSomeOptional: someOptional) {
        doSomething(anotherOptional)
    } else if checkSomeThing() {
        doSomething(nil)
    } else {
       // do something else
    }