Add



Swift Functions

In Swift, function starts with the keyword "func". Then name of the function is written. If function has parameters then we write each parameter along with its type in parentheses, otherwise empty parentheses are written. If function has a return type then it is written with "->" symbol, otherwise nothing is written. If function has a return type then it must have a return statement which returns value according to that type.

    func sayHello(username: String) -> String
    {
	    return "Hello, "+username	
    }

To call this function, we will write as follows:

    let greeting = sayHello(username:"Omer Javed")
    print(greeting)

So now "Hello, Omer Javed" will be printed.

Function without Parameter

The example of function without parameter is given below:

    func getMyValue() -> Int
    {
	    return 8
    }
    let val = getMyValue()
    print(val)

Function without Return Type

The example of function without return type is given below:

    func welcome(fname: String, lname:String)
    {
	    print("Hello, \(fname) \(lname)")
    }

Function with Multiple Return Values

Here is the example of function returning multiple values:

    func getFirstAndLast(myArray:[Int]) -> (firstNum: Int, lastNum:Int)?
    {
	    if myArray.isEmpty
	    {
		    return nil
        }
	    let firstNumber = myArray[0]
	    let lastNumber = myArray[myArray.count-1]
	    return (firstNumber, lastNumber)
    }

Note that to return multiple values, it is not essential at all to write “?” with the tuple. It is made optional (?) just to return nil if array is empty.

Functions with Argument Label

If we provide argument label to any parameter of the function then we write that label name instead while calling that function. Note that still at backend, value is passed to the corresponding variable, not label. For example,

    func showName(myLabel username: String)
    {
	    print(“Name is \(username)”)
    }
    showName(myLabel:”Omer Javed”)

Functions without Parameter Name while Calling

If you write "_" before parameter name (seperated by space) then you do not need to mention parameter name while calling the function.

    func  calculate(firstVal:Int,_ secondVal:Int)
    {
	    return firstVal + secondVal
    }
    let additionResult = calculate(firstVal:6,7)
    print(additionResult)