WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: Does reduce() use short-circuit evaluation?

Forums > Swift

As I understand things, the compiler will short-circuit evaluations once it nows the outcome.

For example

if (a && b && c && d)

if a is false, there is no need to evaluate b, c or d as regardless of their value, the if will always be false.

Now, assume there is an array of Booleans and you want to find out if they are all true. You could do that with a reduce() statement.

array.reduce(true){$0 && $1}

Does the evaluation of the reduce stop once a false value is encountered?

FWIW, I came up with this while writing a function to convert Apples OSErr type to a printable string if possible.

// convert Apple 32-bit int to 4 characters if valid
// 1819304813 = "lpcm"
// 1718449215 = "fmt?"
// -50 = (-50)
func int32ToString(_ error: OSStatus) -> String {
    let chars = Swift.withUnsafeBytes(of: error.bigEndian){ Data($0) }.map{ Character(Unicode.Scalar($0)) }
    return chars.reduce(true){ $0 && $1.isASCII } ? "\"\(String(chars))\"" : "(\(error))"
}

I like eliminating For loops with map() or reduce() statements.

   

.reduce works on the sequence in the array, and processes all the elements.

If you try this in Playground, you can see that reduce is acted upon 11 times.

let boolArray = [false, true, true, true, false, true, false, false, true, true]

let reducedBoolArray = boolArray.reduce(true) {$0 && $1}

print ("Bool Array", boolArray)
print ("Reduced to", reducedBoolArray)

1      

Does the evaluation of the reduce stop once a false value is encountered?

The reduce isn't evaluating a condition, it's just assembling a value based on what you give it. It will go through all the values in the source until it's finished and then present to you the final value. So, no.

   

Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!

Read the book

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.