Latest web development tutorials

Swift function

Swift function is used to accomplish specific tasks separate code blocks.

Swift uses a unified syntax to express a simple C-style functions to complex Objective-C language-style approach.

  • Function declaration: tell the compiler function name, return type, and parameters.

  • Function definition: Providing the entity functions.

Swift function contains the parameter types and return type:


Function definition

Swift-defined functions using the keywordfunc.

Defined functions, you can specify one or more input parameters and a return value type.

Each function has a function name to describe its function. The parameter value of the function name and the type of call that function. Order transfer function parameters must be the same parameter list.

Order of arguments passed in function parameter list must be the same-> After you define the return type of the function.

grammar

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

Examples

Below we define a function called w3big function, the parameters of data type String, the return value of String:

import Cocoa

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

The above program execution output is:

www.w3big.com

Function call

We can call the function through the function name and parameter value corresponding to the type of the order parameter transfer function parameter list must be the same.

Below we define a function called w3big function, the site of the parameter data type String, then we call the function argument passed must be of type String arguments passed after the function body will directly return data type returned a String.

import Cocoa

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

The above program execution output is:

www.w3big.com

Function Arguments

Function can accept one or more parameters, we can also use a tuple (tuple) pass one or more parameters to functions:

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 above program execution output is:

40
45
120

Function without parameters

We can create a function with no parameters.

grammar:

func funcname() -> datatype {
   return datatype
}

Examples

import Cocoa

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

The above program execution output is:

本教程

Tuple return value as the function

Function return value type can be a string, integer, floating-point type.

Tuple is similar to the array, the difference is, the tuple elements can be of any type, using parentheses.

You can have multiple types of values ​​as a composite value returned from the function tuple (tuple).

The following example, the definition of a named minMax (_ :) function of the role is to identify 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)")

minMax (_ :) function returns a tuple of two Int values, you can access them by name those values ​​are marked as min and max, so that the query returns the value of the function at.

The above program execution output is:

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

If you are unsure returned tuple must not nil, then you can return an optional tuple type.

You can place a question mark after the closing parenthesis tuple type to define an optional tuple such as (Int, Int)? Or (String, Int, Bool)?

Note optional tuple type such as (Int, Int)? Tuple contains an optional type such as (Int?, Int?) Is different. The optional tuple type, the entire tuple is optional, and not just each element value tuple.

Front minMax(_:) function returns a two contain Int value tuples. But the function does not perform any security checks on incoming array, if the array parameter is an empty array, as defined above minMax(_:) trying to access array[0] triggers a runtime error.

To deal with this "empty array" issues safely, the minMax(_:) function rewritten to use the optional tuple return type and returns when the array is empty 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 above program execution output is:

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

No return value of the function

Here is w3big (_ :) Another version of the function, the function receives the official website of the tutorial URL parameters, return type is not specified, and direct output String value instead of returning it:

import Cocoa

func w3big(site: String) {
    print("本教程官网:\(site)")
}
w3big("http://www.w3big.com")

The above program execution output is:

本教程官网:http://www.w3big.com

Function Parameter name

Function argument has an external parameter name and a local parameter name.

Local parameter name

Local parameter name in the function of the internal implementation to use.

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

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

import Cocoa

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

The above program execution output is:

1
2
3

External parameter name

You can specify an external parameter name in front of the local parameter names, separated by a space, the external parameter names for parameters passed to the function when the function is called.

You can define the following two functions parameter name 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 above program execution output is:

125

Note that if you provide an external parameter name, then the function is called, you must use an external parameter name.


Variable parameter

Variable parameters can accept zero or more values. When the function is called, you can use a variable parameter to specify the function arguments, their number is uncertain.

Variable parameters by name in the variable type, insert (...) 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", "w3big")

The above program execution output is:

4
3
5
4.5
3.1
5.6
Google
Baidu
w3big

Constants, variables and I / O parameters

Generally the default parameters are constant parameters defined in the function, which is the only parameter you can use a query, you can not change its value.

If you want to declare a variable parameter, you can add var in front so that you can change the value of this parameter.

E.g:

func  getName(var id:String).........

In this case the id values ​​may change in function.

Usually the default parameters are passed by value call, not passed by reference. So incoming parameters within the function change does not affect the original parameters. Just passed a copy of this parameter.

Variable parameters, as described above, can only be changed in the body of the function. If you want a function can modify the value of a parameter, and you want these changes at the end of the function call persists, then you should put this parameter is defined as the input and output parameters (In-Out Parameters).

When defining an input and output parameters, parameter definition before adding inout keyword. Input and output parameters have passed a value of the function, the function value is modified and then spread function, replacing the original value.

Examples

import Cocoa

func swapTwoInts(var a:Int,var b:Int){
    
    let t = a
    a = b
    b = t
}

var x = 0,y = 100
print("x = \(x) ;y = \(y)")

swapTwoInts(x, b:y)
print("x = \(x) ;y = \(y)")

The above program execution output is:

x = 0 ;y = 100
x = 0 ;y = 100

Modification is to use the inout keyword:

import Cocoa

func swapTwoInts(inout a:Int,inout b:Int){
    
    let t = a
    a = b
    b = t
}

var x = 0,y = 100
print("x = \(x) ;y = \(y)")

swapTwoInts(&x, b:&y)
print("x = \(x) ;y = \(y)")

The above program execution output is:

x = 0 ;y = 100
x = 100 ;y = 0

Function type and use

Each function has a specific function of the type of species, the type of the function parameter and return types.

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

Examples are as follows:

import Cocoa

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

The above program execution output is:

2
6

Int above function defines two types of parameters, return values ​​for type Int.

Next we look at the following function, the function defines the parameters of type String, the return value of type String.

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

You can also define the function parameters and any type, as follows:

import Cocoa

func inputstr() {
   print("本教程")
   print("www.w3big.com")
}
inputstr()

The above program execution output is:

本教程
www.w3big.com

Use function type

In Swift, the use of function types As with other types. For example, you can define a constant or variable of type function and the appropriate function assigned to it:

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

Resolution:

"Defining called addition of variables, parameters and return value types are Int , and let this new variable points sum function."

sum and addition have the same type, the above operation is legal.

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

import Cocoa

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

The above program execution output is:

输出结果: 129

Function type as a parameter type, function type as the return type

We can function as a parameter to another parameter:

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(sum, a: 10, b: 20)

The above program execution output is:

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

Nested functions

Nested function refers to the definition of a new function within the function, external function can call functions within a function definition.

Examples are 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 above program execution output is:

-30