A functional learning Tutorial in Swift language _swift

Source: Internet
Author: User
Tags function definition pow

A function is a collection of statements organized together to perform a specific task. Swift functions are similar to simple C functions and complex objective C language functions. It enables us to call internal local and global parameter values through function calls. Like any other language, the Swift function follows the same steps.

function declaration: It tells the compiler about the name of the function, return type, and parameters.

function definition: It provides the actual body of the function.

The Swift function contains the parameter type and the return type.

function definition
in the Swift language, functions are defined by the "func" keyword. When a new definition function, it may need one or several values as the function input as "parameters", it will be processed in the function body and return the value as ' return type ' output.

Each function has a function name that describes the task that the function will perform. To use a function, you call its name function and match the parameter type of the function with its input value, called a parameter. Function arguments are also referred to as "tuples."

The parameters of the function must provide the same order as the function argument list and return a value after->.

Grammar

Copy Code code as follows:

Syntax:
Func funcname (Parameters)-> returntype
{
Statement1
Statement2
---
Statement N
return parameters
}

The student's name is declared as the function "student", the function internally declares a string as the return data type, and when called the function returns the students ' names.
Copy Code code as follows:

Func student (name:string)-> String {
return name
}
println (Student ("The program")
println (Student ("About functions"))

When we use playground to run the above program, we get the following results

The
functions

Call function
Consider the following example, a "display" function for displaying numbers, initialized with the parameter "No1" and holding an integer data type. The parameter "No1" is then assigned to the parameter "a", which points to an integer of the same data type. Now parameter A is returned to the function. Here the display () function holds the integer value, and every time the function is invoked, it returns a whole number.

Copy Code code as follows:

Func display (no1:int)-> Int {
Let A = No1
Return a
}

println (display (100))
println (display (200))


When we use playground to run the above program, we get the following results


200

Parameters and return values
Swift provides flexible function parameters and return values, from simple to complex values. Similar to C and objective C functions can also have multiple forms

Functions with parameters
A function is accessed by its parameter value to the function body. We can pass a single to multivariate parameter value as a tuple to the inside of the function.

Copy Code code as follows:

Func mult (No1:int, no2:int)-> Int {
Return No1*no2
}
println (Mult (2,20))
println (Mult (3,15))
println (Mult (4,30))

When we use playground to run the above program, we get the following results:

120

Functions with no parameters
We may use the Include function without any arguments.

Grammar

Copy Code code as follows:

Func funcname ()-> datatype {
return datatype
}

Here is an example of a function with no parameters:
Copy Code code as follows:

Func votersname ()-> String {
Return "Alice"
}
println (Votersname ())

When we use playground to run the above program, we get the following results

Alice

function with return value
functions can also be used to return strings, integer and floating-point data type values as return types. To find the maximum and minimum number of "LS" in the array function, declare it with the Large,small integer data type.

Array initialized to hold an integer value. The array is then processed and each value in the array is read out and its previous value comparison is written. When the value is smaller than the previous parameter stored in "small", the parameter value stored in "large" returns by calling the function

Copy Code code as follows:

Func ls (array: [INT])-> (Large:int, Small:int) {
var lar = array[0]
var SMA = array[0]
For I in Array[1..<array.count] {
If I < SMA {
SMA = i
else if I > lar {
Lar = i
}
}
Return (Lar, SMA)
}
Let num = ls ([40,12,-5,78,98])
println ("largest number is: \ (num.large) and smallest number is: \ (num.small)")

When we use playground to run the above program, we get the following results

Largest number is:98 and smallest number is:-5

function with no return value
Some functions may declare parameters in a function, but do not have any return values. The following program declares that A and B are passed as arguments to the sum () function. The values of parameters A and B within the function itself are called by calling the function by calling sum (), whose value is printed so that no correlation value is returned.

Copy Code code as follows:

Func sum (a:int, b:int) {
Let A = a + b
Let B = A-b
println (A, B)
}
SUM (20, 10)
SUM (40,10)
SUM (24,6)

When we use playground to run the above program, we get the following results

(a)
(m)
(30, 24)

Returns a function of type Optional
Swift launches the "optional" feature to eliminate problems by introducing a security countermeasure. For example, consider that we declare a function value return type to be an integer, but what happens when the function returns a string value or any one of the 0 values? In this case, the compiler returns an error value. "Optional" is introduced to get rid of these problems.

The optional (Optional) feature will take two forms of ' value ' and ' nil '. We'll mention ' optionals ' using the key to preserve the character "?" to check whether a tuple returns a value or a 0 value.

Copy Code code as follows:

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]) {
println ("Min is \ (bounds.min) and Max are \ (Bounds.max)")
}

When we use playground to run the above program, we get the following results

Min is-6 and Max is 109

' Optionals ' is used to check ' nil ' or garbage values, which consumes a lot of time debugging, making code efficient and readable to users.

function local vs external parameter name local parameter name
Local parameter names are accessed only within functions.

Copy Code code as follows:

Func sample (Number:int) {
println (number)
}

Here the Func sample parameter number is declared as an internal variable because it is accessed internally by the function sample (). Here, "number" is declared as a local variable, but the following statement refers to a variable that can be used outside of a function.
Copy Code code as follows:

Func sample (Number:int) {
println (number)
}
Sample (1)
Sample (2)
Sample (3)

When we use playground to run the above program, we get the following results

1
2
3

External parameter name
the external parameter name allows you to name a function parameter to make them more explicit. Name the arguments for the two functions, and then call the function as follows

Copy Code code as follows:

Func Pow (firstarg a:int, Secondarg b:int)-> Int {
var res = a
For _ in 1..<b {
res = res * A
}
println (RES)
return res
}
Pow (firstarg:5, Secondarg:3)

When we use playground to run the above program, we get the following results

125

Parameter variable type parameter
when we want to define a function that has more than one number of arguments, we can declare a member to be a parameter of variable parameters. Parameters can be specified as variable parameters by (...) After the parameter name.

Copy Code code as follows:

Func vari<n> (Members:n ...) {
For I in the members {
println (i)
}
}
Vari (4,3,5)
Vari (4.5, 3.1, 5.6)
Vari ("Swift", "enumerations", "Closures")

When we use playground to run the above program, we get the following results

4
3
5
4.5
3.1
5.6
Swift
Enumerations
Closures

Constants, variables, and I/O parameters
function By default, parameter ' constants ' are considered, where users can also declare arguments to functions as variables. We have discussed the ' let ' keyword used to declare constant arguments, and the definition of variable parameters is to use the "var" keyword.

The I/o parameter provides the ability to retain parameter values in Swift, even after the function call has been modified. Retains member values at the start of the function parameter definition "inout" keyword.

It derives from the keyword "inout" because its value passes ' in ' to the function and its value is accessed, and its function body is modified, and the function returns to "out" to modify the original argument.

Because its value is inside, the function external modification variable only passes the In-out parameter as a parameter. Therefore, it is not necessary to declare strings, literals as In-out parameters. ' & ' in the previous variable name refers to the parameters passed.

Copy Code code as follows:

Func Temp (inout a1:int, inout b1:int) {
Let T = A1
A1 = B1
B1 = t
}
var no = 2
var CO = 10
Temp (&no, &co)
println ("Swapped values are \ (no), \ (CO)")

When we use playground to run the above program, we get the following results

Swapped values are 10, 2

function types and their usage
Each function follows the specified function by entering the parameters and outputting the desired result.

Copy Code code as follows:

Func inputs (No1:int, no2:int)-> Int {
Return No1/no2
}

Here is an example:
Copy Code code as follows:

Func inputs (No1:int, no2:int)-> Int {
Return No1/no2
}
println (Inputs (20,10))
println (Inputs (36,6))

When we use playground to run the above program, we get the following results

2
6

Here, the function has two arguments No1 and NO2 are initialized as Integer data types, and its return type is also declared as ' int '

Copy Code code as follows:

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

Here, the function is declared as a string data type.

The function may also have an invalid (void) data type to indicate that the function will not return anything.

Copy Code code as follows:

Func Inputstr () {
println ("Swift functions")
println ("Types and its Usage")
}
Inputstr ()

When we use playground to run the above program, we get the following results

Swift functions
Types and its Usage

The above function is declared to have no parameters and the return value of the function is void.

Working with Function types
The function first passes an integer, a floating-point number, or a parameter of a string type, and then it is passed as a constant or a variable to the function as described below.

Copy Code code as follows:

var addition: (int, int)-> Int = Sum

Here ' a ' and ' B ' are declared as parameter variables of the SUM function, where the function adds the two integers and returns:
Copy Code code as follows:

Func sum (a:int, b:int)-> Int {
Return a + b
}
var addition: (int, int)-> Int = Sum
println ("Result: \ (addition (40, 89))")

When we use playground to run the above program, we get the following results

result:129

function types as parameter types and return types
We can also pass the function itself as a parameter type to another function.

Copy Code code as follows:

Func sum (a:int, b:int)-> Int {
Return a + b
}
var addition: (int, int)-> Int = Sum
println ("Result: \ (addition (40, 89))")
Func Another (addition: (int, int)-> Int, A:int, B:int) {
println ("Result: \ (addition (a, b))")
}
Another (sum, 10, 20)

When we use playground to run the above program, we get the following results

result:129
result:30

Nested functions
nested functions call an external function by calling an intrinsic function.

Copy Code code as follows:

Func calcdecrement (fordecrement total:int)-> ()-> Int {
var overalldecrement = 0
Func decrementer ()-> Int {
Overalldecrement = Total
Return overalldecrement
}
Return Decrementer
}
Let Decrem = Calcdecrement (fordecrement:30)
println (Decrem ())

When we use playground to run the above program, we get the following results:

-30

function parameter passing
The syntax format of the function is as follows:
Func function name (argument list)-> return value type {
Statement Group
return value
}
The key word is func.
Multiple argument lists can be separated by commas (,) or without parameters.
Use the arrow "->" to indicate the return value type. The return value has a single value and multiple values. If the function does not return a value, the-> return value type section can be omitted.
If the function has a return value, you need to use the returns statement at the end of the function body, or you can omit the return statement in the body of the function if there are no returned values.
The function definition sample code is as follows:

Copy Code code as follows:

Funcrectanglearea (width:double, height:double)-> Double {
Let area = width * height
Return area
}
Print ("320x480 rectangle's area: \ (Rectanglearea (height:480))")

Passing parameters
Describes several different forms of parameters.
use the name of an external parameter
Provide a name for each parameter that can be used outside the function, called an external parameter name, and modify the Rectanglearea function as follows:
Copy Code code as follows:

Func Rectanglearea (wwidth:double, H height:double)-> Double {
Let area = width * height
Return area
}

Give an "external parameter name" before the local parameter name, separated by a space. The W and h in the definition code are the external parameter names. The calling code is as follows:
Print ("320x480 rectangle's area: \ (Rectanglearea (w:320, h:480)")
If we provide an external parameter name, then the function call must use the external parameter name, so W and H cannot be omitted.

Omitting the name of an external parameter
Swift 2.0 provides the possibility of omitting the name of an external parameter, using an underscore (_) to represent the external argument name when defining a function, as shown in the sample code:

Copy Code code as follows:

Funcrectanglearea (Width:double, _ height:double)-> Double {
Let area = width * height
Return area
}

This allows the function to omit the external parameter name when invoked, as follows:
Print ("320x480 rectangle's area: \ (Rectanglearea (320, 480))")
When you define a function, the first argument does not need an underscore (_), the default first parameter name is omitted, and the other parameter names need to use an underscore (_) symbol if you want to omit it.

parameter Default value
When you define a function, you can set a default value for the parameter, which can be ignored when the function is called. Look at one of the following examples:
Copy Code code as follows:

Func Makecoffee (type:string = "Cappuccino")-> String {
Return "make a cup of coffee (type). "
}

When invoked, the default value is used if the caller does not pass the argument. The calling code is as follows:
Let coffee1 = Makecoffee ("latte")
Let Coffee2 = Makecoffee ()
The final output results are as follows:

Make a cup of latte coffee.
make a cup of cappuccino.

Variable parameters
the number of parameters of a function in Swift can vary, and it can accept an indeterminate number of input type parameters that have the same type. We can do this by adding the (...) Form after the parameter type name. To indicate that this is a variable parameter.
Let's look at an example:

Copy Code code as follows:

Func sum (numbers:double ...)-> Double {
var total:double = 0
For number in numbers {
Total + = number
}
Return Total
}

Here are two calls to the SUM function code:

SUM (100.0)
sum (30, 80)

You can see that the number of parameters passed each time is different.

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.