Swift Functions

Swift functions are self-contained blocks of code that perform specific tasks.

Swift uses a unified syntax to represent functions ranging from simple C-style functions to complex Objective-C-style methods.

  • Function Declaration: Tells the compiler the function's name, return type, and parameters.

  • Function Definition: Provides the body of the function.

Swift functions include parameter types and return value types:


Function Definition

Swift defines functions using the keywordfunc。

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

Each function has a function name that describes its function. You call this function by its name and parameter values of the corresponding types. The order in which function arguments are passed must match the parameter list.

The order in which the function's actual arguments are passed must be the same as the formal parameter list,->Then define the function's return type.

Syntax

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

Example

Below we define a function named example, with a formal parameter of type String and a return value of type String:

import Cocoa

func example(site: String) -> String {
    return (site)
}
print(example(site: "www.example.com"))

The output of the above program execution is:

www.example.com

Function Call

We can call a function by its name and parameter values of the corresponding types. The order in which the function's arguments are passed must match the parameter list.

Below we define a function named example with a formal parameter site of type String. When we call the function, the actual argument passed must also be of type String. After the argument is passed into the function body, it is returned directly, and the returned data type is String.

import Cocoa

func example(site: String) -> String {
    return (site)
}
print(example(site: "www.example.com"))

The output of the above program execution is:

www.example.com

Function Parameters

A function can accept one or more parameters. These parameters are contained within the function's parentheses and separated by commas.

The following example passes the site name name and the site address site to the function example:

import Cocoa

func example(name: String, site: String) -> String {
    return name + site
}
print(example(name: "Example:", site: "www.example.com"))
print(example(name: "Google:", site: "www.google.com"))

The output of the above program execution is:

Example:www.example.com
Google:www.google.com

Functions Without Parameters

We can create functions without parameters.

Syntax:

func funcname() -> datatype {
   return datatype
}

Example

import Cocoa

func sitename() -> String {
    return "Example"
}
print(sitename())

The output of the above program execution is:

Rookie Tutorial

Tuple as a Function Return Value

Function return value types can be strings, integers, floating-point types, etc.

Tuples are similar to arrays, except that the elements in a tuple can be of any type and are enclosed in parentheses.

You can use a tuple type to return multiple values as one compound value from a function.

In the following example, a function named 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(array: [8, -6, 2, 109, 3, 71])
print("最小值为 \(bounds.min) ,最大值为 \(bounds.max)")

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

The output of the above program execution is:

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

If you are not sure that the returned tuple is not nil, you can return an optional tuple type.

You can define an optional tuple by placing a question mark after the right parenthesis of the tuple type, for example (Int, Int)? or (String, Int, Bool)?

Note
Optional tuple types such as(Int, Int)?and tuples containing optional types such as(Int?, Int?)are different. For an optional tuple type, the entire tuple is optional, not just each element value in the tuple.

The previousminMax(_:)function returns a tuple containing twoIntvalues. However, the function does not perform any safety checks on the passed-in array. If thearrayparameter is an empty array, the above-definedminMax(_:)when trying to accessarray[0]will trigger a runtime error.

To safely handle this "empty array" problem, change theminMax(_:)function to use an optional tuple return type, and when the array is empty, returnnil:

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(array: [8, -6, 2, 109, 3, 71]) {
    print("最小值为 \(bounds.min),最大值为 \(bounds.max)")
}

The output of the above program execution is:

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

Functions Without Return Values

Below is another version of the example(_:) function. This function takes the Example official website URL as a parameter, does not specify a return type, and directly outputs a String value instead of returning it:

import Cocoa

func example(site: String) {
    print("Example官网:\(site)")
}
example(site: "http://www.example.com")

The output of the above program execution is:

Example官网:http://www.example.com

Function Parameter Names

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

Local Parameter Names

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

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

In the above example, number is a local parameter name and can only be used inside the function body.

import Cocoa

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

The output of the above program execution is:

1
2
3

External Parameter Names

You can specify an external parameter name before the local parameter name, separated by a space. The external parameter name is used when calling the function to pass the argument to the function.

As follows, you can define the following two function parameter names and call it:

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

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


Variadic Parameters

Variadic parameters can accept zero or more values. When calling a function, you can use a variadic parameter to specify function parameters, and the number is indeterminate.

Variadic parameters are defined by adding (...) after the variable type name.

import Cocoa

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

The output of the above program execution is:

4
3
5
4.5
3.1
5.6
Google
Baidu
Example

Constants, Variables, and I/O Parameters

In general, parameters defined in a function are constant parameters by default, meaning you can only query and use this parameter, but cannot change its value.

If you want to declare a variable parameter, you can add the inout keyword before the parameter definition, so that the value of this parameter can be changed.

For example:

func  getName(_ name: inout String).........

At this point, the name value can be changed within the function.

Generally, the default parameter passing is by value, not by reference. So if the passed-in parameter is changed inside the function, it does not affect the original parameter. What is passed in is only a copy of this parameter.

When a passed-in parameter is used as an input-output parameter, you need to add an & symbol before the parameter name to indicate that this value can be modified by the function.

Example

import Cocoa

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

The swapTwoInts(_:_:) function simply swaps the values of a and b. The function first stores the value of a in a temporary constant temporaryA, then assigns the value of b to a, and finally assigns temporaryA to b.

It should be noted that someInt and anotherInt are both prefixed with & before being passed into the swapTwoInts(_:_:) function.

The output of the above program execution is:

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

Function Types and Usage

Every function has a specific function type, consisting of the function's parameter types and return type.

func inputs(no1: Int, no2: Int) -> Int {
   return no1/no2
}

The inputs function type has two Int parameters (no1, no2) and returns an Int value.

Example:

import Cocoa

func inputs(no1: Int, no2: Int) -> Int {
    return no1/no2
}
print(inputs(no1: 20, no2: 10))
print(inputs(no1: 36, no2: 6))

The output of the above program execution is:

2
6

The above function defines two Int parameter types, and the return value is also of type Int.

Next, let's look at the following function. The function defines a parameter of type String and a return value of type String.

func inputstr(name: String) -> String {
   return name
}

A function can also define a function with no parameters and no return value, as shown below:

import Cocoa

func inputstr() {
   print("Example")
   print("www.example.com")
}
inputstr()

The output of the above program execution is:

Example
www.example.com

Using Function Types

In Swift, using function types is just like using any other type. For example, you can define a constant or variable whose type is a function, and assign an appropriate function to it:

var addition: (Int, Int) -> Int = sum

Explanation:

Define a variable calledadditionwhose parameter and return value types are bothInt, and let this new variable point to thesumfunction.

sumandadditionThey have the same type, so the above operation is legal.

Now, you can use addition to call the assigned function:

import Cocoa

func sum(a: Int, b: Int) -> Int {
   return a + b
}
var addition: (Int, Int) -> Int = sum
print("输出结果: \(addition(40, 89))")

The output of the above program execution is:

输出结果: 129

Function Types as Parameter Types, Function Types as Return Types

We can pass a function as a parameter to another function:

import Cocoa

func sum(a: Int, b: Int) -> Int {
    return a + b
}
var addition: (Int, Int) -> Int = sum
print("输出结果: \(addition(40, 89))")

func another(addition: (Int, Int) -> Int, a: Int, b: Int) {
    print("输出结果: \(addition(a, b))")
}
another(addition: sum, a: 10, b: 20)

The output of the above program execution is:

输出结果: 129
输出结果: 30

Nested Functions

Function nesting refers to defining a new function inside a function; the outer function can call the function defined inside it.

An example is as follows:

import Cocoa

func calcDecrement(forDecrement total: Int) -> () -> Int {
   var overallDecrement = 0
   func decrementer() -> Int {
      overallDecrement -= total
      return overallDecrement
   }
   return decrementer
}
let decrem = calcDecrement(forDecrement: 30)
print(decrem())

The output of the above program execution is:

-30
Other Extensions