Swift Function Parameters and Return Values: In this tutorial, you’ll learn about various user defined functions that takes inputs of various types and returns outputs, with examples.
In the previous tutorial Swift Functions, we learned about functions. Presently, we’ll look at the various ways and types we can create a function in Swift, for example handling input and output in a function.
In this article, you will learn-
- 1 What is a function?
- 2 Function with no parameter and no return value
- 3 Function with no parameter but return value
- 4 Function with parameter but no return value
- 5 Function with parameter and return value
- 6 Example 4: Parameters passed and returns value
- 7 Function with multiple parameters and multiple return values
- 8 Function with argument label
- 9 Example 8: Function with better function call but not as parameter names
- 10 Function with default parameter values
- 11 Function with variadic parameters
- 12 Function with in-out parameters
What is a function?
A function is a group of statements that defines an activity to be performed. The main use of a function is to make the code reusable.
A function is a group of statements that defines an activity to be performed. The main use of a function is to make the code reusable.
Function with no parameter and no return value
These sort of functions don’t take any input and return value.
func funcname() { //statements } OR func funcname() -> () { //statements } OR func funcname() -> Void { //statements }
All the above syntax are legitimate to create a function that takes no parameters and doesn’t return value.
The above syntax func funcname() – > () is likewise equivalent to func funcname() – > Void since Void is only a typealias of (). You can visit Swift Typealias to learn more.
Example 1: No Parameters passed and no return value
func greetUser() { print("Good Morning!") } greetUser()
At the point when you run the above program, the output will be:
Good Morning!
Function with no parameter but return value
These sort of functions don’t take any input parameters however return a worth. To add the return type you need to add arrow(- >) and the return type.
func funcname() -> ReturnType { //statements return value }
Example 2: No Parameters passed but return value
func greetUser() -> String { return "Good Morning!" } let msg = greetUser() print(msg)
At the point when you run the above program, the output will be:
Good Morning!
In the above program, you have defined the return Type to string. Presently, the statement should return a string from the statement inside the function, else you will get an error.
return watchword moves control of the program from body of the function to the function call. In the event that you need to return value from the function, add value after the return keyword.
return “Good Morning!” statement returns worth of type String from the function. Note that the sort of the return and the worth should coordinate.
You can likewise assign the return worth to a variable or a constant. let msg = assigns the return worth to the statement msg. So the statement print(msg) outputs Good Morning! in the console.
On the off chance that you need to neglect the worth, you can essentially use _ as let _ =.
Function with parameter but no return value
Parameters are used to take input in the function. The parameter contains a parameter name and the sort followed by a colon (:). These sort of functions take input parameter however don’t return value.
func funcname(parameterName:Type) { //statements }
Example 3: Parameters passed but no return value
func greetUser(msg:String) { print(msg) } greetUser(msg: "Good Morning!")
At the point when you run the above program, the output will be:
Good Morning!
In the above program, the function acknowledges a single parameter of type String. The parameter must be used inside the function. msg is the name of parameter.
You can consider the function by passing it a string value with the parameter name as greetUser(msg: “Good Morning!”). The msg parameter name is noticeable just inside the function greetUser().
Subsequently, statement print(msg) outputs Good Morning! in the console.
Function with parameter and return value
These type of function take parameters and furthermore return value.
func funcname(parameterName:Type) -> ReturnType { //statements }
Example 4: Parameters passed and returns value
func greetUser(name:String) -> String { return "Good Morning! " + name } let msg = greetUser(name: "Salman") print(msg)
At the point when you run the above program, the output will be:
Good Morning! Salman
In the above program, the function acknowledges a single parameter of type String and furthermore returns value Good Morning! Salman of type String.
Function with multiple parameters and multiple return values
These type of functions take various parameters that are separated by comma and furthermore return different values. You can return various worth in Swift using Tuples. See Swift Tuples to become familiar with it.
func funcname(parameterName:Type, parameterName2:Type ,...) -> (ReturnType, ReturnType...) { //statements }
Example 5: Multiple Parameters passed and multiple return value
func greetUser(name:String, age:Int) -> (String, Int) { let msg = "Good Morning!" + name var userage = age if age < 0 { userage = 0 } return (msg, userage) } let msg = greetUser(name: "Salman", age: -2) print(msg.0) print("You have \(msg.1) coins left")
At the point when you run the above program, the output will be:
Good Morning!Salman You have 0 coins left
In the above program, the function greetUser() acknowledges numerous parameters of type String and Int. The function likewise returns numerous values as a tuple of type String and Int.
To access to each return value, we use file positions 0, 1, … Here, we’ve used msg.0 to access to Good Morning!Salman and msg.1 to access 0.
Using index positions can be unintuitive and unreadable on occasion. We can tackle this issue elegantly by offering names to return value. The above program can likewise be modified as underneath.
Example 6: Multiple return values with name
func greetUser(name:String, coins:Int) -> (name:String, coins:Int) { let msg = "Good Morning!" + name var userCoins = coins if coins < 0 { userCoins = 0 } return (msg, userCoins) } let msg = greetUser(name: "Salman",coins: -2) print(msg.name) print("You have \(msg.coins) coins left")
In this program, the return type is of tuple that contains the variable name with the sort. The fundamental benefit of this is you can access to the outcome using the variable name as msg.name and msg.coins rather than msg.0 and msg.1.
Function with argument label
At the point when you define a function that acknowledges inputs, you can define the input name with the assistance of parameter name. Notwithstanding, there is another sort of name which you can give alongside the parameter name, known as argument label.
The use of argument labels allow a function to be called in an expressive manner, sentence-like way, while as yet giving a function body that is readable and clear in plan.
Each function parameter has both an argument label and a parameter name. By default, parameters use their parameter name as their argument label. However, in the event that you explicitly define the argument name, the argument label is used when calling the function.
The syntax of function with argument name is
func funcname(argumentLabel parameterName:Type)-> Return Type { //statements }
Let’s see this in example below.
Example 7: Function without argument label
func sum(a:Int, b:Int) -> Int { return a + b } let result = sum(a: 2, b: 3) print("The sum is \(result)")
At the point when you run the above program, the output will be:
The sum is 5
In the above example, we have not indicated the argument name, so it takes default parameter name a and b as the argument label while calling the function.
You may see the function call isn’t expressive/sentence when calling the function. You may think it can be made more expressive as English on the off chance that you could settle on the function call as:
let result = sum(of: 2, and: 3)
Presently let’s change the function as:
Example 8: Function with better function call but not as parameter names
func sum(of:Int, and:Int) -> Int { return of + and } let result = sum(of: 2, and: 3) print("The sum is \(result)")
Presently the technique call is expressive. Nonetheless, presently we need to use the parameter name of & and in return of + and to discover the sum of two numbers. Presently, this makes the function body unreadable. Use of a and b rather than of&and would make more sense inside the function body.
For this reason we need to expressly define argument label as:
Example 9: Function with argument labels
func sum(of a :Int, and b:Int) -> Int { return a + b } let result = sum(of: 2, and: 3) print("The sum is \(result)")
In the above program, the function acknowledges two parameter of type Int. The function consider uses the argument label of & and which makes while calling the function as sum(of: 2, and: 3) rather than sum(a: 2, b: 3).
Additionally, the function body uses the parameter name a and b rather than of & and which likewise makes more sense while applying activities.
You can likewise omit the argument name by writing a _ before the parameter name.
func sum(_ a :Int, _ b:Int) -> Int { return a + b } let result = sum(2, 3) print("The sum is \(result)")
Function with default parameter values
You can give default values for any parameter in a function by assigning a worth to the parameter after that parameter’s sort. Giving a default parameter allows you to neglect the parameter while calling the function.
On the off chance that you don’t pass worth to the parameter while calling the function, its default value is used. Nonetheless, on the off chance that you explicitly pass a worth to the parameter while calling, the predetermined worth is used.
func funcname(parameterName:Type = value) -> Return Type { //statements }
Example 10: Function with default parameter values
func sum(of a :Int = 7, and b:Int = 8) -> Int { return a + b } let result1 = sum(of: 2, and: 3) print("The sum is \(result1)") let result2 = sum(of: 2) print("The sum is \(result2)") let result3 = sum(and: 2) print("The sum is \(result3)") let result4 = sum() print("The sum is \(result4)")
At the point when you run the above program, the output will be:
The sum is 5 The sum is 10 The sum is 9 The sum is 15
In the above program, the function sum(of a :Int = 7 , and b:Int = 8) – > Int acknowledges two parameter of type Int yet in addition determines the default worth of parameter a = 7 and b = 8.
On the off chance that you pass value as a parameter in the function call as sum(of: 2, and: 3) at that point 2 and 3 is used rather than parameter default value.
Yet, in the event that you don’t pass the parameter value as sum(), default value 7 and 8 are used as the parameter value.
Function with variadic parameters
A variadic parameter can acknowledge zero or more values of a particular sort. You can indicate variadic parameter by inserting three period characters (…) after the parameter’s sort name.
You generally use a variadic parameter when you need to pass a differing number of input values to the parameter when the function is called. For instance, a list of numbers, a list of alphabets, and so forth
The syntax of function with variadic parameters is:
func funcname(parameterName:Type...) -> Return Type { //statements }
Example 11: Function with variadic parameters
func sum(of numbers:Int...) { var result = 0 for num in numbers { result += num } print("The sum of numbers is \(result)") } sum(of: 1, 2, 3, 4, 5, 6, 7, 8)
In the above program, the function sum(of numbers:Int…) acknowledges a variadic boundary of type Int. A variadic parameter can acknowledge various values separated by comma as sum(of: 1, 2, 3, 4, 5, 6, 7, 8).
The values 1, 2, 3, 4, 5, 6, 7, 8 passed as a variadic parameter are made accessible inside the capacity’s body as a variety of the Int type. In this manner, we can apply for-in circle in the worth with respect to num in numbers.
At the point when you run the above program, the output will be:
The sum of numbers is 36
Note: Swift built in print() function also accepts variadic parameter of type Any.
Any represents to any data type in Swift e.g. Int, Float, Double,String etc.
Function with in-out parameters
At the point when you define the function parameter, the function parameters can’t be changed inside the body. So they are constants by default. Let’s see this in example:
func process(name:String) { if name == ""{ name = "guest" } }
The above program results an incorporate time error since you can’t change the worth of a parameter.
In the event that you need a function to alter a parameter’s worth, you need to define the parameter as in-out parameter. You write an in-out parameter by putting the inout catchphrase just before a parameter’s sort.
In the background, an in-out parameter has a worth that is passed into the function, is altered by the function, and is passed back out of the function to replace the first worth. Accordingly the worth passed in the function call can’t be a consistent. You should declare it as a variable.
The syntax of function with inout parameter is:
func funcname(parameterName:inout Type) -> Return Type { //statements }
Example 12: Function with in out parameter
func process(name:inout String) { if name == ""{ name = "guest" } } var userName = "" process(name: &userName) print(userName)
At the point when you run the above program, the output will be:
guest
In the above program, we have declared a function that acknowledges inout parameter name so the parameter can be changed/altered inside the body of the function.
You should use ampersand (&) sign straightforwardly before a variable’s name when you pass argument to an in-out parameter so it tends to be adjusted by the function.
Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.