UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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.

2      

.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)

3      

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.

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.