12. Functions in Swift

Swift can help you to add different lines of code in one block. You can assign some meaningful name to your code block and the block can perform one particular task for you. This block is called Function.

Declaration of the Function

Function declaration is as follows:

func nameOfTheFunction(){
     your code here
}

Write the word func and assign some name to the function with two small brackets (). After these small brackets add curly start and end brackets { }. All your required code will come in between two brackets.

Once you are done with writing your code block, you can call this function from anywhere by using nameOfTheFunction with ( ) small brackets. Check this example: You have function sayHello() with println, call this function with sayHello() and “Hello from function” will display on screen

func sayHello(){
     println("Hello from function")
}

// function call
sayHello()

 

Function return type

After calculation, you can return some value from function. You must tell your function about variable type which you want to return. Add arrow sign with variable type after function declaration, return your variable and you are done.

func nameOfTheFunction() -> variable_type{
     your code here
     return your_variable
}

Check following example: sayHello function has a return type String. You can call this function and get the returned value.

func sayHello() -> String{
    var message = "Hello from Function"
    return message
}

// sayHello function returns a string
var returnedValue = sayHello()
println(returnedValue)

 

Function with parameters

Function can accept value from caller. To catch these values function must have some parameters. Parameters can be one or more.

func nameOfTheFunction(parameter_name : type){
     your code here
}

Check this example: this function takes String as a parameter. You can call this function and pass some string variable.

func sayHello(name : String){
     println("Hello from \(name)")
}

sayHello("Khan")

Function can take one or more than one parameters and it can return the value as well

func nameOfTheFunction(parameter_name : Int, parameter_name : Int) -> Int{
     your code here
     return your_variable
}

Check this example: this function takes two integer parameters, adds them and returns an integer value. You can call this function with 2 integer values and you can get returned value as well.

func Add(value1 : Int, value2 : Int) -> Int{

    return value1 + value2
}

var result = Add(9, 10)
println(result)

 

Continue with advanced topic….

 

Download file from GitHub