Saturday, June 14, 2014

Swift In Depth - Day III

Functions and Closures

a sample function is declared as below 

func greet(name : String, day : String) -> String 
{
return "Hello \(name) good \(day)"
}

greet ("Bob" , "morning")

we can use tuple to return multiple return values

fund getGasPrices() -> (Double, Double, Double)
{
return (3.5, 4.5, 6.7)
}

getGasPrices()

note that when there is only one return type, we don't need to have tuple brackets. 

function can also have variable argument list 

fund sumOf (numbers: Int ….) -> int 
{
var sum = 0; 
for number in numbers
{
sum += number
}
return sum
}

this function can be called like below 

sumOf()
sumOf(1,2,3)

Function can also be nested! - not sure what is the real use, but as per the explanation it says functions can be nested so that we can organise the code in a function that is long or complex. 

fund returnFifteen: () -> int 
{
var sum = 10
fun add()
{
sum+= 5
}
add()
return sum 
}

return 15

function can return another function ! 

func makeincrementer() -> (Int -> Int)
{
func incrementer (value : Int) -> Int 
{
value +=1 
}
return incrementer
}

var incremented = returnIncrementer()
incrementer(7)

A function can take another as its arguments 

func hasAnyMatches (list : int[], condition: Int -> Bool ) -> Bool 
{
var hasMatch  = false 
for value in list 
{
if condition(value)
{
hasMatch = true
}
return hasMatch
}

fund lessThanTen(value : Int ) -> Bool
{
if (value < 10)
return true
} return false

var numbers = [10,11,12]
bool match = hasAnyMatches (numbers, lessThanTen)

functions are actually a special case of closures. You can write a closure without a name by surrounding code with braces ({}). Use in to separate 
the arguments and return type from the body 

numbers.map(
{
(number: int) -> Int in 
let result = 3 * number 
return result
}

)

No comments:

Post a Comment