Learning Swift: Functions [Parameters]

Learning Swift: Functions [Parameters]

 

In the previous post on functions, we started with defining and calling functions. 

Today we will go a bit deeper into function parameters or popularly called arguments.

Parameters are the inputs for the function.

If you recall from the previous video, this is the factorial function we studied. This factorial function has only one parameter i.e. number.

 

func factorial (number: Int) -> Int{
    var factorial = 1
    var temp = number
    while(temp>1){
        factorial =  factorial * temp
        temp = temp - 1
    }
    return factorial
}

 

Here the number is the input for the factorial function.

There are functions with one parameter and function with more than one parameters also.

To see an example of the function with zero parameters we will remove the parameter number from the function factorial. And add a constant number 7 inside the function.

func factorial () -> Int{
    let number = 7
    var factorial = 1
    var temp = number
    while(temp>1){
        factorial =  factorial * temp
        temp = temp - 1
    }
    return factorial
}

//functionName(paramName: paramValue)

print("Factorial is \(factorial(number: 7))")

 

But we see an error in the print function where we call our function. The error says, “Argument passed to call that takes no arguments

Learning Swift: Functions [Parameters] errors

This is happening because the function we defined has no parameters but the function we are calling has one parameter. To remove the error we remove number: 7 from the function call. And now there is no error and we get our output 5040.

Learning Swift: Functions [Parameters] error gone

func factorial () -> Int{
    let number = 7
    var factorial = 1
    var temp = number
    while(temp>1){
        factorial =  factorial * temp
        temp = temp - 1
    }
    return factorial
}

//functionName(paramName: paramValue)

print("Factorial is \(factorial())")

 

Now to study an example of a function with two parameters, we will define a function product, having two parameters x and y, both integers, and the function will return the product of x and y as an integer.

//product of two numbers

func product(x: Int, y: Int) -> Int {
    return x*y
}

print("Product of 6 and 14 is \(product(x: 6, y: 14))")

 

We can see that this function has two parameters in the definition x and y. And we call the function product with values of x as 6 and y as 14 and get the product 84.

Learning Swift: Functions [Parameters] product

Similarly, there can be functions with three or even four or five parameters.

With this, we complete the function parameters. In next post, we will focus on the return types.

You can find the source code for this post here.

If you have any questions or comments do leave them in the comment section below.