Last active
April 12, 2017 18:55
-
-
Save durul/0ce22a07904953c3804237cc11783afc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Write three functions that compute the sum of the numbers in a given list using a for-loop, a while-loop. | |
// Part 2 | |
var series = [1, 2, 3, 4, 5, 6] | |
let realSum = series.reduce(0,{$0 + $1}) | |
// Normal Closure | |
var timesTenClosure: (Int) -> Int = { $0 * 10 } | |
// Problem 1 | |
// for-loop Part 2 | |
func sum(from: Int, to: Int, closure: (Int) -> (Int)) -> Int { | |
var sum = 0 | |
for i in series { | |
sum += closure(i) | |
} | |
return sum | |
} | |
sum(from: 0, to: 10, closure: timesTenClosure) | |
// while-loop Part 2 | |
func sum(from: Int, to: Int, closure: (Int) -> (Int)) -> Int { | |
var whileLoopSum = 0 | |
var i = 0 | |
while i < series.count { | |
whileLoopSum += series[i] | |
i = i + 1 | |
} | |
return whileLoopSum | |
} | |
sum(from: 0, to: 10, closure: timesTenClosure) | |
// Trailing Closure Extremely Short Version | |
sum(from: 0, to: 10, closure: { $0 * 10 }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment