English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Swift Function Parameters and Return Values

In this article, you will learn about different user-defined functions, which will take different types of input and return output through examples.

In the previous articleSwift functionsNow that we have learned about functions, we will explore different ways and types of creating functions in Swift, that is, handling input and output in functions.

Functions with no parameters and no return values

These types of functions do not accept any input or return values.

func funcname() {
    //Statement
}
or
func funcname() -> () {
    //Statement
}
or
func funcname() -> Void {
    //Statement
}

All the above syntaxes are valid for creating functions without parameters and without return values.

The above syntax func funcname()->() is also equivalent to func funcname()->void, because void is just a type alias for (). You can accessSwift type aliasfor more information.

Example1no parameters passed, no return value

func greetUser() {
    print("Good Morning!")
}
greetUser()

When you run the above program, the output will be:

Good Morning!

Functions with no parameters but a return value

These types of functions do not accept any input parameters but return a value. To add a return type, you need to add an arrow (->()) and return type.

func funcname() -> ReturnType {
    //Statement
    return value
}

Example2no parameters passed but a return value

func greetUser() -> String {
    return "Good Morning!"
}
let msg = greetUser()
print(msg)

When you run the above program, the output will be:

Good Morning!

In the above program, you defined the return type as String. Now, this statement must return a string from within the function; otherwise, you will throw an error.

The return keyword transfers control from the function body to the function call. If you need to return a value from the function, add the value to return after the return keyword.

The return "Good Morning!" statement returns a value of type String from the function. Please note that the type and value of the return must match.

You can also assign the return value to a variable or a constant. Let msg = assign the return value to the constant msg. Therefore, the statement print(msg) outputs"Good Morning!".

If you want to ignore this value, just use an underscore _, as let _.

Functions with parameters but no return values

Parameters are used to input in the function. Parameters include parameter name and type, followed by a colon (:). These types of functions use input parameters but do not return values.

func funcname(parameterName: Type) {
    //Statement
}

Example3: Parameter passing without return value

func greetUser(msg: String) {
    print(msg)
}
greetUser(msg: "Good Morning!")

When you run the above program, the output will be:

Good Morning!

In the above program, the function accepts a single parameter of type String. The parameter can only be used within the function. msg is the name of the parameter.

You can call the function greetUser(msg: "Good Morning!") by passing a string value with the parameter name msg. The parameter name is only visible within the greetUser() function.

Therefore, the print(msg) statement outputs "Good Morning!".

Functions with parameters and return values

These types of functions use parameters and return values.

func funcname(parameterName: Type) -> ReturnType {
    //Statement
}

Example4: Passed parameters and returned values

func greetUser(name: String) -> String {
    return "Good Morning! " + name
}
let msg = greetUser(name: "Jack")
print(msg)

When you run the above program, the output will be:

Good Morning! Jack

In the above program, the function accepts a single parameter of type String and also returns a value of type String, "Good Morning! Jack".

Functions with multiple parameters and multiple return values

These types of functions use multiple parameters separated by commas and also return multiple values. You can use tuples to return multiple values in Swift.

func funcname(parameterName: Type, parameterName2: Type ..., ) -> (ReturnType, ReturnType...) {
    //Statement
}

Example5: Passed multiple parameters and multiple return values

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: "Jack", age: -2)
print(msg.0)
print("You have \(msg.1) coins left")

When you run the above program, the output will be:

Good Morning!Jack
You have 0 coins left

In the above program, the function greetUser() accepts multiple parameters of type String and Int. The function also returns multiple values, of type String and Int.

To access each return value, we use index position 0,1, … Here, we use msg.0 to access "Good Morning!Jack" and msg.1 Accessing "0".

Using index positions can sometimes be unclear and unreadable. We can elegantly solve this problem by naming the return values. The above program can also be rewritten in the following way.

Example6has multiple return values with names

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: "Jack", coins: -2)
print(msg.name)
print("You have \(msg.coins) coins left")

In this program, the return type is a tuple containing variable names of that type. The main advantage of this is that you can use variable names msg.name and msg.coins instead of msg.0 and msg.1 to access the result.

Function with argument labels

When defining a function that accepts input, you can define the input name with the help of the parameter name. However, there is another name that can be used with the parameter name, called the argument label.

The use of argument labels allows for a call to the function in an expressive manner, similar to a sentence, while still providing a readable and clear function body.

Each function parameter has an argument label and a parameter name. By default, the parameter uses its parameter name as its argument label. However, if you explicitly define the parameter name, the argument label will be used when calling the function.

The syntax for a function with argument labels is

func funcname(argumentLabel parameterName: Type)-> Return Type {
    //Statement
}

Let us see this in the following example.

Example7:不带参数标签的函数

func sum(a: Int, b: Int) -> Int {
    
    return a + b
}
let result = sum(a: 2, b: 3)
print("The sum is \(result\)")

When you run the above program, the output will be:

The sum is 5

在上面的示例中,我们没有指定参数标签,因此在调用函数时它将使用默认参数名称a和b作为参数标签。

当调用函数时,您可能会注意到函数调用不是表达性的/句子。如果您可以将函数调用设置为:

let result = sum(of: 2, and: 3)

现在让我们将函数更改为:

Example8:具有更好的函数调用但不作为参数名称的函数

func sum(of: Int, and: Int) -> Int {
    return of + and
}
let result = sum(of: 2, and: 3)
print("The sum is \(result\)")

现在,方法调用是可表达的。但是,现在我们必须使用参数名称of&and,return of + and 来查找两个数字的和。现在,这使得函数体可读性较差。在函数体内使用a和b代替of&and将更有意义。

为此,我们必须将参数标签明确定义为:

Example9:带有参数标签的函数

func sum(of a: Int, and b: Int) -> Int {
    return a + b
}
let result = sum(of: 2, and: 3)
print("The sum is \(result\)")

在上述程序中,该函数接受Int类型的两个参数。函数调用使用参数标签of&and,这在调用函数sum(of: 2, and: 3),而不是 sum(a: 2, b: 3)

另外,函数主体使用参数名称a和b,而不是of&and,这在应用操作时也更有意义。

您还可以通过在参数名称前写一个下划线 _ 来省略参数标签。

func sum(_ a: Int, _ b: Int) -> Int {
    return a + b
}
let result = sum(2, 3)
print("The sum is \(result\)")

具有默认参数值的函数

您可以为函数中的任何参数提供默认值,方法是在该参数的类型之后为该参数分配一个值。提供默认参数可以使您在调用函数时忽略该参数。

如果在调用函数时未将值传递给参数,则使用其默认值。但是,如果在调用时将值显式传递给参数,则使用指定的值。

func funcname(parameterName: Type = value) -> Return Type {
    //Statement
}

Example10:具有默认参数值的函数

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)\)

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 takes two Int parameters and specifies the parameter a=7and b=8the default value.

If you pass value as a parameter in the function call, sum(of: 2, and: 3) is used2and3will be used instead of the parameter default value.

However, if you do not pass the parameter value as sum(), then the default value7and8as parameter values.

Function with variable arguments

Variable arguments can accept zero or more values of a specific type. You can specify a variable argument by inserting three dots (...) after the parameter type name.

Variable arguments are typically used when you need to pass various numbers of input values to parameters when calling a function. For example, a list of numbers, a list of letters, and so on.

The syntax for a function with variable arguments is:

func funcname(parameterName: Type...) -> Return Type {
    //Statement
}

Example11: function with variable arguments

func sum(of numbers: Int...) {
    var result = 0
    for num in numbers {
        result += num
    }
    print("The sum of the numbers is \(result)")
}
sum(of: 1, 2, 3, 4, 5, 6, 7, 8)

In the above program, the function sum(of numbers: Int...) accepts variable arguments of type Int. Variable arguments can accept multiple values separated by commas sum(of: 1, 2, 3, 4, 5, 6, 7, 8)

as values passed as variable arguments1,2,3,4,5,6,7,8It can be used as an Int array within the function body. Therefore, we can use for-in the loop is applied as for num in numbers.

When you run the above program, the output will be:

The sum of the numbers is 36

Note: Swift's built-in print() function also accepts arbitrary types of variable arguments.

Any represents any data type in Swift, such as Int, Float, Double, String, and so on.

Function with input/output parameters

When defining function parameters, you cannot modify function parameters within the body. Therefore, by default, they are constants. Let's see an example:

func process(name: String) {
    if name == ""{
        name = "guest"
    }
}

The above program will cause a compile-time error because you cannot change the value of the parameter.

If you want the function to modify the parameter value, you need to define the parameter as in-out parameter. You can write input/output parameter.

In the background, an in-The out parameter has a value that is passed into the function, modified by the function, and then passed back out of the function to replace the original value. Therefore, the value passed in the function call cannot be a constant. You must declare it as a variable.

The syntax for functions with inout parameters is:

func funcname(parameterName: inout Type) -> Return Type {
    //Statement
}

Example12With inout parameters

func process(name: inout String) { 
    if name == ""{
        name = "guest"
    }
}
var userName = ""
process(name: &userName)
print(userName)

When you run the above program, the output will be:

guest

In the above program, we declared a function that accepts an inout parameter so that we can change/Change the parameter name.

When passing parameters to in-When passing out parameters, you must use the & symbol directly before the variable name to allow the function to modify it.