Swift - Functions

Functions


Let's discuss about Functions.

To declare a function, use func keyword. Add the parameters and their data type inside a parentheses.

The return type is separated by the -> symbol.

A general function syntax would be,

func ( : ) -> {

}

func welcome (guest : String, meridian : String) -> String {
return "Hello \(guest), \(meridian)."
}

welcome (name : "Alice", meridian : "Good Morning")

Swift supports a great feature when it comes to returning values from functions. You can combine multiple parameters and return them as Tuples.

func daysOfWeek(week : [String]) -> (firstDay : String, secondDay : String) {
let fristDay : String = week[0]
let secondDay : String = week[1]

return (firstDay, secondDay)
}

Here, firstDay and secondDay are two String type parameters that are grouped and returned together.

Lets look how the values that are returned and handled in swift.

let (first, second) = daysOfWeek(["Monday", "Tuesday", "Wednesday"])

print (first) // Monday

print (second) // Tuesday

The tuple, (first, second) and created as (String, String) type and stores the value that are returned from function.

Functions can access a variable number of arguments, and they are collected in an array.

func average(numbers : Int...) -> Int {
var averageValue = 0
for number in numbers {
averageValue += number
}
return averageValue
}

Comments

Popular posts from this blog

Swift - Strings

What's new in Swift 4!

Swift - Classes