Skip to content

Instantly share code, notes, and snippets.

@pbrewczynski
Created June 19, 2014 14:05
Show Gist options
  • Save pbrewczynski/2caaa761c6238a3cb724 to your computer and use it in GitHub Desktop.
Save pbrewczynski/2caaa761c6238a3cb724 to your computer and use it in GitHub Desktop.
//“Rewrite the closure to return zero for all odd numbers.”
//Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/pl/jEUH0.l
var numbers : UInt[] = [20, 19, 10, 13, 432, 432432, 80];
// Could this be more efficient:
let mapped : Array<UInt> = numbers.map({
(number : UInt) -> UInt in
let multiplier : UInt = ~(number % 2 + (UInt.max-1));
return number * multiplier;
});
// Than (using ifs) this: ?
let mapped2 : Array<UInt> = numbers.map({
(number : UInt) -> UInt in
if (number % 2) == 1 {
return 0;
} else {
return number;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment