o7planning

Swift Functions Tutorial with Examples

  1. Defining Function
  2. Rules call functions and methods
  3. The function returns a value
  4. Function returns multiple values
  5. Function with Variadic parameter
  6. Function inside a function
  7. Function Type
  8. The function returns a function

1. Defining Function

In Swift, a function is defined by the "func" keyword, the specific function name, the function can have 0 or more parameters, and with or without a return type.
Syntax define a function:
// A function has return type
func functionName(parameters) -> returntype  
{
   // Statements....
    return value;
} 
// The function has no return type
func functionName(parameters)
{
    // Statements...
}
Here's a function named sayHello, have a parameter of String type , and returns a String.
MyFirstFunction.swift
import Foundation

// Define a function
// Function name: sayHello
// Parameter: name, type of String
// Return: String
func sayHello(name:String) -> String { 
    // If 'name' is empty.
    if name.isEmpty  {
        // Returns, and Ends the function
        return "Hello every body!"
    }
    // If 'name' is not empty, this code will be executed.
    return "Hello " + name 
} 
// Define a function, no parameters, no returns type.
func test_sayHello()  { 
    // Call sayHello function, pass empty string.
    var greeting1 = sayHello("")  
    print("greeting1 = " + greeting1);
    
    // Call sayHello function, pass "Swift" as parameter.
    var greeting2 = sayHello("Swift") 
    print("greeting2 = " + greeting2); 
}
Edit the source file main.swift to test the function that you just created.
main.swift
import Foundation

// Call test_sayHello() function.
test_sayHello()
Running the example.
greeting1 = Helloo everybody!
greeting2 = Hello Swift

2. Rules call functions and methods

Rules call a function for Swift >= 2.1
  • First parameter to methods and functions should not have required argument label.
  • Other parameters to methods and functions should have required argument labels.
  • All parameters to Constructors should have required argument labels.
RulesCallFunc.swift
import Foundation

// name1, name2 are Labels
func sayHello(name1: String, name2: String)   { 
    print("Hello " + name1);
    print("Hello " + name2); 
}  
func test_sayHello()    {  
    let tom = "Tom"
    let jerry = "Jerry"
    
    // Rules to Call function (Or method):
    // First parameter should not have required argument labels
    // Others parameter should have required argument labels.
    sayHello(tom, name2: jerry)  
}

3. The function returns a value

The return statement stops the execution of a function and returns a value from that function.
FunctionExample1.swift
import Foundation

// Define a function to sum 3 number type of Int, return Int.
func sum(a: Int, b: Int, c: Int) -> Int  { 
    // Declare a variable type of Int
    var ret:Int = a + b + c 
    return ret 
}  
// Define a function to find the largest number in 3 numbers.
func max(a: Int, b: Int, c: Int) -> Int { 
    // Declare varriable 'm', assign value = a.
    var m = a
    
    // Check if m < b then assgin m = b.
    if m < b  {
        m = b
    } 
    // If m > c then return m.
    if m >  c  { 
        // Ends function
        return m;
    } 
    return c 
}

4. Function returns multiple values

In Swift, a function can returns multiple values, essentially, this function returns a tuple. The Tuple is a sequence of values placed in ( ), and separated by commas . Each value has a name that can access it.
ReturningTupleExample.swift
import Foundation

// Defina a function named getMinMax
// Input is an array of Int.
// The function returns two values: 
// The largest number and the smallest number in the array.
func getMinMax(arr: [Int]) -> (min: Int, max: Int)   { 
    // If array has no elements, return (0,0).
    if arr.count == 0  {
        // End function
        return (0, 0)
    } 
    // Declare 2 variables 'mi', 'ma'.
    // assigned by the first element of the array.
    var mi: Int = arr[0]
    var ma: Int = arr[0]  
    for a in arr  { 
        if mi > a  {
            mi = a
        }
        if  ma  <  a  {
            ma = a
        }
    } 
    return (mi, ma)
} 
// Test getMinMax function.
func test_returningTupleExample()    { 
    // An array of Int.
    var years: [Int] = [2000, 1989, 1975, 2005, 2016] 
    // Call getMinMax function.
    var y = getMinMax(years) 
    print("Max = \(y.max)") 
    print("Min = \(y.min)")  
}
Edit main.swift to test example.
main.swift
import Foundation

test_returningTupleExample()
Running the example.
Max = 2016
Min = 1975

5. Function with Variadic parameter

Swift uses "variableName: DataType..." to mark a parameter is Variadic. See the example below which is about a function with Variadic parameter and using this function.
VariadicParamsFunction.swift
import Foundation

// A function with Variadic parameter: nums
// Parameter nums: Like an array of Int.
func sum(nums: Int...) -> Int { 
    var retNumber : Int = 0  
    for n in nums {
        retNumber = retNumber + n
    } 
    return retNumber 
} 
// Using function, with Variadic parameter:
func test_sum()    { 
    // Call sum function, pass 3 parameters.
    var sum1 = sum(1, 2, 3) 
    print("sum(1, 2, 3) = \(sum1)") 
    // Call sum function, pass 4 parameters.
    var sum2 = sum(1,4, 5, 7) 
    print("sum(1,4, 5, 7) = \(sum2)") 
}
Running the example.
sum(1, 2, 3) = 6
sum(1, 4, 5, 7) = 17

6. Function inside a function

Swift allows you to write a function within another function, this function is used internally of father function.
NestedFunction.swift
import Foundation

// Function return tax amount, base on country code & salary.
func getTaxAmount(countryCode:String, salaryAmount:Int) -> Int  { 
    // A function to caculate tax amount in United States.
    func getUsaTaxAmount( salaryAmount: Int)  -> Int {
        // 15%
        return 15*salaryAmount/100
    }  
    // A function to caculate tax amount in Vietnam.
    func getVietnamTaxAmount( salaryAmount:Int)  -> Int {
        // 10%
        return 10 * salaryAmount/100
    } 
    if countryCode == "US" { 
        return getUsaTaxAmount(salaryAmount) 
    } else if countryCode == "VN" { 
        return getVietnamTaxAmount(salaryAmount) 
    } 
    // Other countries (5%)
    return  5 * salaryAmount / 100 
}

7. Function Type

In Swift, each function has a type of function, see the following function:
func sum(a: Int,  b: Int)  -> Int   {
    return a + b;
}
Function type is:
(Int,Int) -> (Int)

8. The function returns a function

ReturningFunction.swift
import Foundation

// A function to caculate tax amount in United States.
// Function type is: (Int) -> (Int)
func getUsaTaxAmount(salary: Int)  -> Int { 
    return 15 * salary / 100
} 
// A function to caculate tax amount in Vietnam.
// Function type is: (Int) -> (Int)
func getVietnamTaxAmount(salary: Int) -> Int  { 
    return 10 * salary / 100
} 
// A default function to caculate tax amount.
// Function type is: (Int) -> (Int)
func getDefaultTaxAmount(salary: Int) -> Int { 
    return 5 * salary / 100
} 
// This function return a function.
func getTaxFunction(countryCode: String) ->  ( Int -> Int )  { 
    if countryCode == "US"  {
        return getUsaTaxAmount 
    } else if countryCode == "VN"  { 
        return getVietnamTaxAmount
    }
    return getDefaultTaxAmount 
}  
// Test
func  test_returningFunction()  { 
    var countryCode = "US"
    print("Country Code = " + countryCode) 
    // Get function.
    var taxFunction =  getTaxFunction(countryCode)  
    var salary = 10000 
    print("Salary = \(salary)")
    
    var taxAmount = taxFunction(salary) 
    print("Tax Amount = \(taxAmount)")
}
Edit main.swift to test example.
main.swift
import Foundation 
test_returningFunction()
Running the example.
Country Code = US
Salary = 10000
Tax Amount = 1500