Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Swift function


May 21, 2021 Swift


Table of contents


A separate block of code that the Swift function is used to complete a specific task.

Swift uses a uniform syntax to represent simple C-style functions to complex Objective-C-style methods.

  • Function declaration: Tells the compiler the name of the function, returns the type and parameters.

  • Function definition: Provides the entity of the function.

The Swift function contains the argument type and the return value type:


The function definition

Swift defines functions that use the keyword func.

When you define a function, you can specify one or more input parameters and one return value type.

Each function has a function name to describe its functionality. T he function is called by its name and the parameter value of the corresponding type. The arguments of the function must be passed in the same order as the argument list.

The arguments of the function must pass in the same order as the list of parameters, and the return value type of the function is later defined.

Grammar

func funcname(形参) -> returntype
{
   Statement1
   Statement2
   ……
   Statement N
   return parameters
}

Instance

Below we define a function named youj, the data type of the parameter is String, and the return value is String:

import Cocoa

func youj(site: String) -> String {
    return site
}
print(youj("www.w3cschool.cn"))

The output of the above program execution is:

www.w3cschool.cn

The function is called

We can call a function by its name and the parameter value of the corresponding type, and the arguments of the function must be passed in the same order as the argument list.

Below we define a function named youj, the data type of the parameter site is String, after which we call the argument passed by the function must also be string type, the argument passed into the function body, will be returned directly, the returned data type is String.

import Cocoa

func youj(site: String) -> String {
    return site
}
print(youj("www.w3cschool.cn"))

The output of the above program execution is:

www.w3cschool.cn

Function arguments

The function can accept one or more arguments, and we can also use tuple to pass one or more arguments to the function:

import Cocoa

func mult(no1: Int, no2: Int) -> Int {
   return no1*no2
}
print(mult(2, no2:20))
print(mult(3, no2:15))
print(mult(4, no2:30))

The output of the above program execution is:

40
45
120

Without argument functions

We can create functions without arguments.

Grammar:

func funcname() -> datatype {
   return datatype
}

Instance

import Cocoa

func sitename() -> String {
    return "W3Cschool教程"
}
print(sitename())

The output of the above program execution is:

W3Cschool教程

The u-group returns a value as a function

Function return value types can be strings, integers, floats, and so on.

Unlike arrays, elements in a group can be of any type, using parentheses.

You can use tuple types to have multiple values returned from a function as a composite value.

In the following example, a function called minMax is defined to find the minimum and maximum values in an Int array.

import Cocoa

func minMax(array: [Int]) -> (min: Int, max: Int) {
    var currentMin = array[0]
    var currentMax = array[0]
    for value in array[1..<array.count] {
        if value < currentMin {
            currentMin = value
        } else if value > currentMax {
            currentMax = value
        }
    }
    return (currentMin, currentMax)
}

let bounds = minMax([8, -6, 2, 109, 3, 71])
print("最小值为 \(bounds.min) ,最大值为 \(bounds.max)")

The minMax(_:) function returns a metagroup containing two Int values, which are marked min and max so that they can be accessed by name when querying the return values of the function.

The output of the above program execution is:

最小值为 -6 ,最大值为 109

If you are not sure that the metagroup returned must not be nil, you can return an optional group type.

Can you define an optional group by placing a question mark after the closing parenthesis of the group type, such as (Int, Int)or (String, Int, Bool)?

Attention
Optional group types such (Int, Int)? W ith the yuan group contains optional (Int?, Int?) I t's different. Optional group type, the entire group is optional, not just the value of each element in the group.

The previous minMax(_:) returns a metagroup with Int values. However, the function does not perform any security checks on incoming array parameter is an empty minMax(_:) triggers a run-time error when trying to access array[0]

To safely handle this "empty minMax(_:) to return the type using an optional group, and return nil when the nil

import Cocoa

func minMax(array: [Int]) -> (min: Int, max: Int)? {
    if array.isEmpty { return nil }
    var currentMin = array[0]
    var currentMax = array[0]
    for value in array[1..<array.count] {
        if value < currentMin {
            currentMin = value
        } else if value > currentMax {
            currentMax = value
        }
    }
    return (currentMin, currentMax)
}
if let bounds = minMax([8, -6, 2, 109, 3, 71]) {
    print("最小值为 \(bounds.min),组大值为 \(bounds.max)")
}

The output of the above program execution is:

最小值为 -6,组大值为 109

There is no return value function

Here's youj Another version of the function, which receives the W3Cschool tutorial website URL parameters, does not specify the return value type, and outputs the String value directly instead of returning it:

import Cocoa

func youj(site: String) {
    print("W3Cschool教程官网:\(site)")
}
youj("http://www.w3cschool.cn")

The output of the above program execution is:

W3Cschool教程官网:http://www.w3cschool.cn

The name of the function argument

Function parameters have an external argument name and a local parameter name.

The name of the local parameter

Local parameter names are used inside the implementation of the function.

func sample(number: Int) {
   println(number)
}

The number in the above example is a local parameter name and can only be used in the body of the function.

import Cocoa

func sample(number: Int) {
   print(number)
}
sample(1)
sample(2)
sample(3)

The output of the above program execution is:

1
2
3

The name of the external parameter

You can specify an external parameter name before the local parameter name, separated by a space in the middle, and the external parameter name is used to pass the argument to the function when it is called.

Here are two function argument names you can define and call:

import Cocoa

func pow(firstArg a: Int, secondArg b: Int) -> Int {
   var res = a
   for _ in 1..<b {
      res = res * a
   }
   print(res)
   return res
}
pow(firstArg:5, secondArg:3)

The output of the above program execution is:

125

Attention
If you provide an external parameter name, the function must use an external parameter name when it is called.


Variable parameters

Variable parameters can accept zero or more values. When a function is called, you can specify a function argument with variable parameters, the number of which is indeterminate.

Variable parameters are added after the variable type name (... ) way to define.

import Cocoa

func vari<N>(members: N...){
    for i in members {
        print(i)
    }
}
vari(4,3,5)
vari(4.5, 3.1, 5.6)
vari("Google", "Baidu", "W3CSchool")

The output of the above program execution is:

4
3
5
4.5
3.1
5.6
Google
Baidu
W3CSchool

Constants, variables, and I/O parameters

Generally the default parameters defined in a function are constant parameters, that is, this parameter you can only query to use, can not change its value.
If you want to declare a variable argument, you can add the inout keyword before the parameter definition so that you can change the value of the parameter.
For example:

func getName(_name: inout Sting).....

At this point this name value can be changed in the function.

Generally, the default parameter pass is called by a pass value, not by a pass reference. S o the incoming argument changes within the function and does not affect the original argument. Only a copy of this parameter is passed in.

When an incoming argument is used as an input-output argument, the symbol needs to be added before the argument name to indicate that the value can be modified by the function.

Instance:

func swapTwoInts(_a: inout Int, _b: inout Int) {

    let temporaryA = a

    a = b

    b = temporaryA

}

var x = 1

var y = 5

swapTwoInts(&X, &y)

print("x 现在的值\(x),y 现在的值\(y)")

SwapTwoInts : simple exchange of values a and b with the function. The function first deposits the value of a into a temporary constant tempoaryA, then assigns the value of b to a, and finally assigns the value of tempoaryA to b.

It is important to note that someInt anotherInt is passing in swapTwoInts (

: :) the function, it's all prefixed.

The above procedures are performed as follows:

x 现在的值 5,y 现在的值 1