How Do You Rewrite This Closure to Return Zero for all Odd Numbers

var numbers = [20, 19, 7, 12]


// Closure

numbers.map({ (number: Int) -> Int

in

let result = 3 * number

return result


})


Thank you.

God bless, Genesis 1:3

Answered by pierredrks in 333565022

You can change your return to


return result & 1 == 1 ? 0 : result
Accepted Answer

You can change your return to


return result & 1 == 1 ? 0 : result

Nice way.


It is better than using modulo (%) operator, which can yield a negative result and forces to use abs (test with var numbers = [20, -19, 7, 12])


return abs(result % 2) == 1 ? 0 : result


or to test for non even:


return result % 2 != 0 ? 0 : result

It is better than using modulo (%) operator …

Indeed.

Determining if something is odd or even has been a recent topic of must interest for Swift Evolution. You should check out SE-0225 Adding isMultiple to BinaryInteger and also the acceptance post for that proposal.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Thanks, interesting document.


In fact, I thought % was really a modulo and not a remainer. Which leads to problems with negative numbers.

Thanks so much for the replied.

I'll try all that.

By the way how come the parameter and output are regular integers and not an array? Weren't you taking in an array?

How come it still works even though your parameter and output are not arrays like. Shouldn't it be like:


var numbers = [20, 19, 7, 12]

numbers.map({ (number: [Int]) -> [Int]


Thanks in advance.

When a closure passed to the `map` method of Array of Int, it needs to represent a transformation of each element.


Each element is of type Int, no? In the case you have shown, the closure gets an Int and returns an Int, and the `map` method calls the closure repreatedly for all its elements.

Hi. I hope they make that built-in function isMultiple and also add isOdd, isEven to make coding easier.

Thanks. I hope you're enjoying the new Apple Campus there:-)

Hi. In result & 1, what kind of operator is &? I'm only seen &&

Thank you.

& is the bitwise AND operator.


It combines the bits of 2 numbers with a AND operation.


See Swwift language reference in the Advanced operators chapter.

This seems to work and is nice and easy:

numbers.map({ (number: Int) -> Int in   return number % 2 == 0 ? number : 0 })

How Do You Rewrite This Closure to Return Zero for all Odd Numbers
 
 
Q