Created
May 23, 2015 21:59
-
-
Save 0xjorgev/0a2c7fce6e5199063393 to your computer and use it in GitHub Desktop.
Swift Functions Part One
This file contains hidden or 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
import UIKit | |
/* | |
Swift Functions on theswift.ninja! | |
http://www.theswift.ninja/swift/ | |
*/ | |
//Function of type Void (doesn't not return nothing) | |
func addition(a:Int, b:Int){ | |
print("\(a+b)") | |
} | |
addition(2, 2) | |
//Function of type Int | |
func addition2(a:Int, b:Int) -> Int { | |
return a+b | |
} | |
addition2(2, 3) | |
//Function of type Int | |
func addition3(a:[Int]) -> Int { | |
var sum:Int = 0 | |
for i in a { | |
sum += i | |
} | |
return sum | |
} | |
var evenNumbers = [2,4,6,8,10] | |
addition3(evenNumbers) | |
addition3([1,2,3,4]) | |
//Function of type Int | |
func addition4(a:Int... ) -> Int { | |
return addition3(a) | |
} | |
addition4(1,2,3,4,5) | |
//Function type Function (it returns another function) | |
func addition5(a:Int, b:Int) -> () -> Int { | |
return {c in a + b} | |
} | |
let sum = addition5(3,3) | |
sum() | |
//Curring | |
func additon6(x: Int) -> (Int -> Int) { | |
return { y in return x + y } | |
} | |
let res = additon6(5)(6) | |
//Wildcard pattern | |
func addition7(_ a:Int = 0, _ b:Int = 0){ | |
print("\(a+b)") | |
} | |
addition7(1, 3) | |
//Functions of type Int that recieves functions as parameters | |
func operate (a:Int, b:Int, fn:(Int, Int)->Int) { | |
fn(a,b) | |
} | |
var add: (Int, Int) -> Int = { | |
return $0 + $1 | |
} | |
let result = add(4,5) | |
result | |
//Error a is let type | |
func operate3(a:Int) -> Int { | |
return a + 1 | |
} | |
func operate4(var a:Int) -> Int { | |
a++ | |
return a | |
} | |
operate4(3) | |
operate(1,2,{ (a:Int, b:Int)->(Int) in return a+b }) | |
operate(1,2,{(a, b)->(Int) in return a+b }) | |
operate(1,2,{(a, b) in a+b }) | |
operate(1,2){ $0+$1 } | |
operate4(5) | |
//Find out more on http://theswift.ninja |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment