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 betrue
for the overall expression to also betrue
.If either value is
false
, the overall expression will also befalse
. In fact, if the first value isfalse
, the second value won’t even be evaluated, because it can’t possibly make the overall expression equate totrue
. This is known as short-circuit evaluation.