Functions and Closures in Swift
Here are top 13 things to know about Functions in Swift.
In Swift, you define functions to perform tasks with data.
- Functions let you organize your code into small, repeatable chunks, like so:
func sayHello() {
print("Hello")
}
sayHello() // prints "Hello"
2. Functions can return a value to the code that calls them, it returns by using the arrow (->) symbol:
func usefulNumber() -> Int {
return 123
}
let anUsefulNumber = usefulNumber() // 123
3. You can pass parameters to a function inside the parentheses, which it’s able to use to do work.
func addNumbers(firstValue: Int, secondValue: Int) -> Int {
return firstValue + secondValue
}
let result = addNumbers(firstValue: 1, secondValue: 2) // 3
4. A function can return a single value, as we’ve already seen, but it can also return multiple values, in the form of a tuple. When you call a function that returns a tuple, you can access its value by index or by name (if it has them):
func processNumbers(firstValue: Int, secondValue: Int) -> (doubled: Int, quadrupled: Int)
{
return (firstValue * 2, secondValue * 4)
}
// Accessing by number:
processNumbers(firstValue: 2, secondValue: 4).1 // = 16
// Same thing but with names…