Swift Language Tutorial for Beginner 9 - Function

In Swift Language Tutorial for Beginner 8 - Set, we understand the use of collection types in Swift, and now let’s take a look at the function in Swift - Function.

The syntax of functions in Swift is a little different from C/C+, Java, and may be considering integration with Objective-C (OC), so some of the features of the OC language are retained when defining and calling, which takes a little time for developers who are accustomed to C/C++ and Java to adapt.

Define a function

In Swift, you need to use the keyword “func” to define the function, follow the function name, then define the arguments in parentheses, indicate the return value type with “->”, and finally follow the function body.

1
func function_nameparameter list)-> returnning data type {}

Let’s define a function according to this definition, and the function function is to simply determine whether a number passed in is greater than 10. The definitions are as follows:

1
2
3
4
5
6
7
func isMoreThanTen(count:Int) -> Bool {
if count > 10 {
return true
}else
return false
}
}

Each parameter is defined in the form of:

1
parameter_name: data type

Multiple parameters are separated by a “,” sign.

If there are no arguments, you can use an empty parenthesis, such as:

1
2
3
func myFunc1()->String{
return "No parameter"
}

If you do not need a return value, you can define it in two ways

  1. Indicates that the return type is Void
1
2
3
func myFunc2() -> Void {
print("No parameter And No returnning value")
}
  1. Ignore “->” directly
1
2
3
func myFunc3() {
print("Ignore returnning value")
}

Invoke a function

Note: When calling functions, the differences with C/C++ and Java are mainly in the parameter list

Now, let’s call the function defined in the previous section: isMoreThanTen

1
isMoreThanTen(count: 9)

Note: Parameter names cannot be omitted when calling

1
isMoreThanTen(20) // Compile Error

Understand the internal and external names of parameters

Let’s take a look at the case where there are multiple parameters, first define a function with three parameters as follows:

1
2
3
4
func myFunc5(param1: Int,param2: Int,param3: Int) -> Int {
// Param1, param2, param3 used here are the internal naming of parameters
return param1+param2+param3
}

Here, we introduce a unique noun in swift: the internal naming of the parameter. When calling we need to give the corresponding parameter internal name, such as calling myFunc5, we need to write like this:

1
myFunc5(param1: 1, param2: 2, param3: 3)

Note that although you give the internal name of each parameter, it does not mean that you can change the order of the parameter list,The following call cannot be compiled

1
myFunc5(param3: 1, param2: 2, param1: 3) // Compile Error

We can also define external parameter names for the function, such as adding the external function name to myFunc5 above, as follows:

1
2
3
func myFunc5(out1 param1: Int,ou2 param2: Int,ou3 param3: Int) -> Int {
return param1+param2+param3
}

Param1, param2, param3 used here are the internal names of the parameters, and out1, out2, out3 are the external parameter names.

When there is an external parameter name, the call must be made using the external parameter name,So the example above becomes:

1
myFunc5(out1: 1, ou2: 2, ou3: 3)

Internal parameters cannot be compiled, such as:

1
myFunc5(param1: 1, param2: 2, param3: 3) // Compile Error

Of course, it is also possible to display the ignore of external parameter names, which can be defined like this:

1
2
3
func myFunc5(param1:Int,_ param2:Int , _ param3:Int) -> Int {
return param1 + param2 + param3
}

Note: Places places placeholders for external parameter names with the “_ “ sign,This allows parameter names to be ignored when invoked. as:

1
myFunc5(param1: 1, 2, 3)

Parameter default value (default)

When defining the parameters of a function, we can also specify default values for the parameters, and when calling, use the default values of the parameters for those that do not have an actual parameter given. as:

Define the function myFunc8 and set the default parameter param2 to 10 and param3 to 5

1
2
3
func myFunc8(param1:Int,param2:Int = 10 ,param3:Int = 5) -> Int {
return param1 + param2 + param3
}

You can call myFunc8 like this

  1. Each parameter is passed a value
1
myFunc8(param1: 1, param2: 1, param3: 1)
  1. Values are passed only for parameters that do not have default values set
1
myFunc8(param1: 10)
  1. Pass values to some parameters
1
myFunc8(param1: 20, param3: 30)

Note that parameters with default values do not need to be arranged at the end of the parameter list

Variable length parameter

In swift, it is allowed to define an indeterminate number of arguments using “…” as in the function below, such as multiple smoothly indeterminate integer arguments in the function below, which can actually be accessed by parameter names like a list.

1
2
3
4
5
6
7
func myFunc10(param:Int...){
var sum=0;
for count in param {
sum += count
}
print(sum)
}

When called, you can give different numbers of parameters, such as:

1
2
myFunc10(param: 1,2,3,4,5)
myFunc10(param: 12,2,3)

Unlike Java, java that becomes the last parameter when it is necessary to become a parameter, there is no such restriction in swift, such as:

1
2
3
4
5
6
7
func myFunc11(param1:Int...,param2:String)  {
var sum=0;
for count in param1 {
sum+=count
}
print("\(param2):\(sum)")
}

Call the method:

1
myFunc11(param1: 1,2,3, param2: "hello")

inout Parameter

Usually, after passing an argument to a function, if the value of the changed parameter is changed in the function, the changed value cannot be taken out of the range of the function body. So what if you need to bring it out? Swift provides parameters of type inout.

1
2
3
func myFunc12( param:inout Int){
param += 1
}

In myFunc12, in order to bring out the changed param value in the function (not in a practical way of returning the value), you can add inout before the parameter type.

When calling, some special processing is required, such as calling myFunc12:

1
2
3
4
var para = 10;

myFunc12(param: &para)
print(para)

Note: The & symbol is added before the variable name, It can be understood as a “take address” operation in other languages.

The function type

In Swift, functions can also be used as a data type, called function pointers in C/C++. The syntax for the declaration of a function type is to remove the function body from the syntax of the function definition, such as:

1
var addFunc:(Int,Int)->Int

This way, we declare a function variable with two Int arguments and an Int return type. For this variable, we can have several ways of assigning values.

  1. Directly assign a defined function, such as:
1
2
3
4
5
6
7
func myFunc13(param1:Int,param2:Int) -> Int {
return param2+param1
}
addFunc = myFunc13

// 执行
addFunc(1, 2)
  1. Returned by a function

We construct a function to assign a value to this variable.

1
2
3
4
5
6
7
8
9
10
func myFunc15() -> (Int,Int)->Int {
return {(param1:Int, param2:Int) in
return param1 + param2
}
}

addFunc = myFunc15()

// Invoke
addFunc(1, 2)

Of course, we can also write:

1
2
3
4
5
6
7
8
9
10
11
func myFunc16() -> (Int,Int)->Int {
func subFunc(param1:Int, param2:Int)->Int{
return param1 + param2
}
return subFunc
}

addFunc = myFunc16()

// 执行
addFunc(1, 2)
  1. Defines an anonymous function

Code as the following:

1
2
3
4
5
6
7
addFunc = {
(param1:Int,param2:Int) in
return param1+param2
}

// Invoke
addFunc(2,3)

Use a function type in an argument

Since functions can be used as a data type, they can also be used in parameter lists, such as:

For example: Defines a function that can pass in a function type of type (Int,Int)->Int,

1
2
3
func myFunc14(param:(Int, Int)->Int) {
print(param(1, 2))
}

Next, you can use the addFunc defined in the previous section as the calling myFunc14 parameter:

1
myFunc14(param: addFunc)

本文标题:Swift Language Tutorial for Beginner 9 - Function

文章作者:Morning Star

发布时间:2022年01月18日 - 08:01

最后更新:2022年01月18日 - 09:01

原始链接:https://www.mls-tech.info/app/swift/swift-tutorial-9-function-en/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。