Swift Learning-07--Functions

Source: Internet
Author: User
Tags mathematical functions types of functions

Function

A function is a separate piece of code that accomplishes a particular task, and you can identify the function of a function by naming it, which can be used to ' invoke ' the function to accomplish its task when needed.

Swift's unified function syntax is very flexible and can be used to represent any function, from a simple C-style function without a parameter name, to a complex, external parameter OC style function with local parameters, which can provide default values to simplify function calls, which can also be treated as incoming parameters, as outgoing parameters, and That is, once the function execution is finished, the passed parameter value is modified

In swift, each parameter has a type that consists of a function's parameter value type and a return value type, and you can treat the function type as if it were any other ordinary variable type, so that the function can be used more simply as an argument to another function, or it can be returned from another function. The definition of a function can be written in the definition of other functions, so that the function can be encapsulated within the scope of the nested function.

Definition and invocation of a function

When you define a function, you can define one or more values that have a name and type, as input to a function, called a parameter, or you can define a value of a type as the output at the end of a function execution, called the return type

Each function has a function name that describes the task performed by the function, using a function name to invoke the function, and passing it a matching input value (called an argument), the argument of the function must match the order of the parameters in the function parameter.

Func greet (person:string), string{

Let greeting = "Hello," + person + "!"

return greeting

}

The definition of a function, prefixed with func, specifying the function return type, is represented by the return arrow, followed by a hyphen followed by a right angle bracket, and by the name of the return type.

The definition describes the function of what it expects to receive as a parameter and what type of result it returns at the end of execution.

Print (Greet (person: "Ahhh"))

Note: prient (_:separator:terminator:) The first parameter of the function does not have a label, while the other parameter is optional because it has a default value

Func Greenagain (person:string), string{

Return "Hello," + person + "!"

}

Print (Greenagain (person: "Houdehcneg"))

Type of function and return value

function parameters and return values are very flexible in swift, and you can define any type of function, from simple functions with only one unnamed parameter to complex complex functions with expression parameter names and different parameter options

No parameter function

function can have no arguments,

Func SayHelloWorld ()-string{

Return "hello,world!"

}

Print (SayHelloWorld ())

Although this function has no arguments, it requires a stack of parentheses after the function name in the definition, and when called, it is necessary to write a pair of parentheses in the function name

Multi-parameter functions

Functions can have multiple input parameters, which are contained within the parentheses of the function, separated by commas

Func greet (person:string,alreadygreeted:bool), string{

If alreadygreeted {

Return Greenagain (Person:person)

}else{

return greet (Person:person)

}

}

Print (Greet (person: "TIMW", Alreadygreeted:true))

No return value function

The function can have no return value, the following is another version of the greet (person:) function, which prints a string value directly instead of returning it:

Func Greet2 (person:string) {

Print (person)

}

Because this function does not require a return value, there is no return arrow (-) and return type in the definition of the function

Note: Strictly speaking, although no return value is defined, greet (person:) The function still returns a value, and a function that does not define a return value returns a special Void value, which is actually an empty tuple, without any elements that can be written ()

Note: The return value can be ignored, but a function that has a return value defined must return a value that will result in an edit error if no value is returned at the bottom of the function definition

Multiple return value functions

You can use a tuple (tuple) type to return multiple values from a function as a composite value

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,-5,2,109,-21,71])

Print ("Min is \ (bounds.min), Max is \ (Bounds.max)")

It is important to note that members of tuples do not need to be returned from functions in tuples because their names are already specified in the function's return type.

Optional tuple return type

If the tuple type returned by the function is likely to have ' no value ' for the entire tuple, you can use the optional (optional) tuple return type to reflect the fact that the entire tuple can be nil, and you can define an optional tuple by placing a question mark after the closing parenthesis of the tuple type, for example (Int,int)?

Note: Optional tuple types such as (Int,int)? With tuples include optional types such as (Int?,int?) is a different, optional tuple type, and the entire tuple is optional, not an element value in a tuple

The previous example Minmax (array:) The function returns a tuple containing two Int values, but the function does not perform any checks on the incoming array, and if an array parameter passed in is an empty one, it triggers a run-time error and, in order to handle the empty array problem safely, Minmax (array:) function is rewritten as the return type of an optional tuple, and nil is returned when the array is empty

Func minMax2 (array: [INT])-(min:int,max:int)? {

If Array.isEmpty {

return Nil

}else{

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)

}

}

You can use optional bindings to check MINMAX2 (array:) Whether the function returns an existing tuple or nil

If Let Bounds2 = MinMax2 (array: [8,-6, 2, 109, 3, 71]) {

Print ("Min is \ (bounds.min) and Max is \ (Bounds.max)")

}

function parameter label and parameter name

Each function parameter has a parameter label and a parameter name, the parameter label is used when calling the function, the parameter label of the function must be written in front of the corresponding parameter, the parameter name is used in the function implementation, by default, the function parameter uses the parameter name as the parameter label of the magistrate

All parameters must have a unique name,

Specifying parameter labels

You can specify its parameter label before the function name, and the middle space is split

Func someFunction (Argumentlabel arametername:int) {

Print (Arametername)

}

SomeFunction (Argumentlabel:5)

Ignore parameter labels

If you don't want to add a label to a parameter, you can use an underscore (_) instead of an explicit parameter label

Func SomeFunction2 (_ Firstparametername:int, Seconedparamerer:int) {

Print (Firstparametername + seconedparamerer)

}

SomeFunction2 (8, Seconedparamerer:8)

If a parameter has a label, then the tag must be used to mark the parameter at the time of the call.

Default parameter values

You can define a default value (Deafult value) in the function body by assigning a value to a parameter to any function, and when the default value is defined, calling this function can ignore the argument

Func SomeFunction3 (Parameterwithoutdefault:int,parameterwithdefault:int = 12) {

Print (Parameterwithdefault + parameterwithoutdefault)

}

SomeFunction3 (Parameterwithoutdefault:8, Parameterwithdefault:8)

SomeFunction3 (Parameterwithoutdefault:8)

Parameters that do not have a default value are placed at the top of the function parameter list, in general, parameters that do not have a default value are more important, and parameters that do not have a default value are first guaranteed to be the same in the order of function calls, and colleagues make the same function more clear when invoked under different circumstances.

Variable parameters

A mutable parameter can accept 0 or more values, and when a function is called, you can use a variable parameter to specify an indeterminate number of input values that a function parameter can be passed in, by adding (...) after the variable type. The way to define mutable parameters

The incoming value of a mutable parameter becomes an array of the secondary type in the function body.

Func Arithmeticmean (_ numbers:double ...)-double{

var total:double = 0

For number in numbers {

Total + = number

}

Return total/double (Numbers.count)

}

Print (Arithmeticmean (45.4,78.5,96.2,151,151,2551,96.58))

Note: A function can have a maximum of one variable parameter

Input and OUTPUT parameters

The function parameter is a constant by default, and attempting to change the value of the parameter in the body of the function will result in an edit error. This means that you cannot change the parameter value incorrectly, and if you want a function to modify the value of the parameter and want to persist after these modified function calls, you should define the parameter as an input-output function

When defining an input-output function, add the InOut keyword before the parameter definition, an input-output parameter has the value of the passed-in function, the value is modified by the function, and then the outgoing function, replacing the original value,

You can only pass variables to the input and output parameters, you cannot pass in constants or literals, because these quantities cannot be modified, when the parameters passed in as input and output parameters, you need to add a & to the parameter name, indicating that the value can be modified by the function

Note: input and output parameters cannot have default values, and mutable parameters cannot be marked with InOut

Func swaptwoints (_ a:inout int,_ b:inout Int) {

Let Temporarya = a

A = b

b = Temporarya

}

Call

var someint = 3

var antherint = 107

Swaptwoints (&someint, &antherint)

Print ("A is: \ (someint), B is: \ (antherint)")

From the above example, we can see the original values of Someint and Antherint in Swaptwoints (_:_:) Functions are modified, although they are defined outside the function body

Note: the input and output parameters are not the same as the return values, and the swaptwoints function above does not define any return values, but the values of Someint and Anotherint are still modified, and the input and output parameters are another way for the function to have an effect outside the function body.

function type

Each function has a specific function type, and the type of the function consists of the parameter type of the function and the type of the return value.

Func Addtwoints (_ A:int, _ B:int), int{

Return a + b

}

Func Multiplytwoints (_ A:int, _ B:int), int{

return a * b

}

In this example, two simple mathematical functions are defined, addtwoints and multiplytwoints, both of which receive two int values, returning an int value,

The type of these two functions is (int,int), int, which can be interpreted as ' This function type has two arguments of type int and returns a return value of type int

The following example, no parameters, no return values

Func Printhelloworld () {

Print ("hello,world!")

}

The type of this parameter is: (), void, or ' no parameter ' and returns a value of type void '

Using function types

In swift, using a function type is like using a different type, for example, you can define a constant or variable with a type of function and assign the appropriate function to it

var mathfunction: (int,int)->int = addtwoints (_:_:)

This code can be understood as. Define a variable called mathfunction, which is ' a function that has two parameters of type int and returns a value of each int type ' and makes the new variable point to the Addtwoints function

Mathfunction and addtwoints have the same type, so this assignment process is allowed in the Swift type check (Type-check)

Now you can use Mathfunction to invoke the assigned function.

Print ("Result: \ (mathfunction (2,5))")

Different functions with the same matching type can be assigned to the same variable, just like a variable of a non-function type

Mathfunction = multiplytwoints (_:_:)

Print ("Result: \ (mathfunction (5,8))")

Just like any other type, when assigning a function to a constant or variable, you can let Swift infer its function type

Let anthermathfunction = addtwoints

Anthermathfunction is inferred as (int,int)->int type

function type as parameter type

You can use a function type (int, int) and int as the parameter type of another function, so you can leave a part of the function implementation to the caller of the function to provide

Func Printmathresult (_ Mathfunction: (int, int), int, _ A:int, _ B:int) {

Print ("Result: \ (mathfunction (b))")

}

Printmathresult (Addtwoints (_:_:), 8, 5)

This example defines the Printmathresult (_:_:_:) function, which has three parameters, the first parameter is called Mathfunction, the type is (int, int), int, you can pass in any of these types of functions, the second and third arguments are called a and B, their type is Int, and these two values are the input values of the given function

When Printmathresult (_:_:_:) When called, it is passed into the addtwoints function and the integers a and B, which calls Addtwoints (_:_:) with the incoming A and B, and outputs the result

Printmathresult (_:_:_:) The function is to output the result of the invocation of another mathematical function of the appropriate type, which does not care how the incoming function is implemented. Only care about the incoming function is not a correct type, which makes Printmathresult (_:_:_:) Ability to pass a subset of functionality to the caller implementation in a type-safe (type-safe) manner

function type as return type

You can use the function type as the return type of another function, you need to do is to write a complete function type after the arrow (-)

The following example defines two simple functions, both of which are of type int

Func Stepforward (_ Input:int), int{

return input + 1

}

Func Stepbackward (_ Input:int), int{

Return input-1

}

The return type of the following function is a function of type int (int),

Func choosestepfunction (Backward:bool)-(Int)-int{

Return backward? Stepbackward (_:): Stepforward (_:)

}

You can use Choosestepfunction (backward:) To get one of two functions

var currentvalue = 3

Let Movenearertozero = choosestepfunction (Backward:currentvalue > 0)

Print (Movenearertozero (currentvalue))

Nested functions

All the functions you see in this chapter so far are called global functions, which are defined in the global domain, and you can also define functions in other function bodies called nested functions (nested functions)

By default, nested functions are invisible to the outside world, but can be called by their peripheral functions (enclosing function), and a peripheral function can return one of its nested functions so that the function can be used in other domains

You can override the Choosestepfunction (backward:) function in a way that returns a nested function

Func ChooseStepFunction2 (Backward:bool)-(int)-int {

Func Stepforward (input:int), Int {return input + 1}

Func Stepbackward (input:int), Int {return input-1}

Return backward? Stepbackward:stepforward

}

var currentValue2 =-4

Let MoveNearerToZero2 = choosestepfunction (Backward:currentvalue > 0)

Print (MoveNearerToZero2 (currentValue2))

Swift Learning-07--Functions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.