Home > Enterprise >  What order are if statement conditions checked
What order are if statement conditions checked

Time:08-19

I created an extension to check if values in an array are unique

extension Sequence where Iterator.Element: Hashable {
    func unique() -> [Iterator.Element] {
        var seen: Set<Iterator.Element> = []
        return filter { seen.insert($0).inserted }
    }
}

The issue with this is that the check is O(n) complexity so within my function that uses this, I have a condition to disable this check.

if !valuesAreUnique && (values.unique() != values) {
    fatalError("Values must be unique.")
}

So my question is, will values.unique() always get executed in this if statement? In order to avoid that I would have to layer it like so, correct?

if !valuesAreUnique {
    if (values.unique() != values { // This is only ran if valuesAreUnique
        fatalError("Values must be unique.")
    }
}

Or if valuesAreUnique is false, then the checks just stop?

CodePudding user response:

via https://docs.swift.org/swift-book/LanguageGuide/BasicOperators.html

The logical AND operator (a && b) creates logical expressions where both values must be true for the overall expression to also be true.

If either value is false, the overall expression will also be false. In fact, if the first value is false, the second value won’t even be evaluated, because it can’t possibly make the overall expression equate to true. This is known as short-circuit evaluation.

  • Related