Wednesday, October 7, 2015

Swift Functions - Basics I

fun is used to declare a function. A function declaration can have zero or more parameters, written as name:Type. the function return type is written after the name of the function after parameter list with -> 

func greet(name:String, day:String) -> String 
{
return “Hello \(name), today is \(day).”
}

We can call a function by following its name with a list of arguments in parentheses. The first argument need not have its name, the subsequent ones should have. 

for e.g. 


greet(“anna” day:”tuesday”)

Swift can have Function that return multiple values 

func minmax(array:[Int]) -> (min:Int, max:Int)
{
return (5,10)
}

let bounds = minmax([5,6,7,8,9,10])

print ("min is \(bounds.min) and max is \(bounds.max)")

The return types can be optional also and optional return values is represented with ? 

for e.e.g 

func minmax(array:[Int]) -> (min:Int, max:Int) ?
{
return (currentMin, currentMax)
}

if (let bounds = minmax([1,2,3,4]))
{
       print("min is :\(bounds.min) and max is: (bounds.max)")
}

There are lot more in functions! 


references:
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html

No comments:

Post a Comment