Created
March 5, 2015 05:57
-
-
Save SimplGy/4f2f06fac902466acf3f to your computer and use it in GitHub Desktop.
Playing around with functions as params and return types in Swift
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
func double (a:Int) -> Int { return a * 2 } | |
func quadruple (a:Int) -> Int { return a * 4 } | |
double(10) | |
quadruple(10) | |
// ------------Q: How do I accept a function as a parameter? | |
func modifyInt (num a:Int, modifier fn: Int -> Int) -> Int { | |
return fn(a) | |
} | |
func modifyIntAlt ( | |
#num:Int, // Arg[0] is an int | |
#fn: Int -> Int // Arg[1] is a function that takes and returns an int | |
) -> Int // modifyIntAlt returns an Int | |
{ | |
var result = fn(num) | |
return result | |
} | |
modifyInt(num: 10, modifier: double) | |
modifyIntAlt(num: 10, fn: quadruple) | |
// ------------Q: How do I return a function? | |
func getFn ( | |
idx:Int // This function accepts an Int | |
) -> // This function returns... | |
Int -> Int // The return type is a fn that takes and returns Int | |
{ | |
var fn = double | |
if idx == 4 { | |
fn = quadruple | |
} | |
return fn | |
} | |
modifyInt(num: 10, modifier: getFn(4)) | |
func buildIncrementor() -> () -> Int { | |
var i = 0 | |
func incrementor () -> Int { | |
i++; | |
return i | |
} | |
return incrementor | |
} | |
var inc = buildIncrementor() | |
inc() | |
inc() | |
inc() | |
// ------------Q: How do I work with variable arguments? | |
func average(numbers:[Int]) -> Int { | |
var sum = 0 | |
for n in numbers { | |
sum += n | |
} | |
return sum / numbers.count | |
} | |
// Done this way, we can support both array and arg syntax | |
func average(numbers:Int...) -> Int { | |
return average(numbers) | |
} | |
average(100,50,10) | |
average([100,50,10]) // same-same but different | |
// ------------Q: How do I set default parameters? | |
func multiplyBy(a:Int, multiplier:Int = 10 ) -> Int { | |
return a * multiplier | |
} | |
multiplyBy(10, multiplier:2) | |
multiplyBy(10) | |
// ------------Q: How do I manipulate a reference to an external primitive? | |
func increment(inout a:Int) { | |
a++ | |
} | |
var a = 1 | |
increment(&a) | |
a | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment