Getting started with Swift Functions

Source: Internet
Author: User
Tags types of functions

Getting started with Swift Functions

1. Functions in swift are of the upper type, so functions can also be used as parameters and returned results.


2. Define the form keyword name (parameter list)-> return value type. The following is an example of returned tuples.

        func addNumber(a:Int,b:Int) -> (addResult : Int, timesResult : Int) {                        return(a+b, a*b)                }                let result =  addNumber(1, 2)                println(result.addResult)
Input two parameters a and B and add them together. The result of multiplication is returned in the form of a tuples. There can be no parameters, but there must be () indicating the parameters. If no return value is returned, the values before-> and {must be omitted. No return value indicates that we have not defined the return value, but the function actually returns a void value. It is actually an empty tuples and can be written as () without any elements ()


3. function parameter name:

As we can see in the function form above, the parameter names a and B are just a local variable. We can only use them within the defined number of letters, not externally.

If a function has multiple parameters, we may not know the explicit meaning of these parameters during use. In this case, we can use the External Parameter Name to solve this problem.

Now there is a function that requires the input of three functions, the height of the parents and the code of Men and Women 1 and 2 to request the height of the child. As follows:


                func getPersonHeight(height1:Float,hieght2:Float,isBoy:Int)  -> Float{                        if isBoy == 1 {                          return  45.99 + 0.78 * (height1+hieght2) / 2 + 5.29                        } else {                              return 37.85+0.75 * (height1+hieght2) / 2 + 5.29            }                }

When we use it elsewhere, we do not display the meaning of these three numbers, which may cause a value transfer error. Now we only need to use the external names of the parameters to clearly indicate their meanings during the call. Add the external name of the parameter to the front of the local name and open it with spaces.


                func getPersonHeight(height1:Float,hieght2:Float,isBoy:Int)  -> Float{                        if isBoy == 1 {                          return  45.99 + 0.78 * (height1+hieght2) / 2 + 5.29                        } else {                              return 37.85+0.75 * (height1+hieght2) / 2 + 5.29            }                }

Code when no external name is called

Let height = getPersonHeight (170,180, 1 );

Code when an external name is called

Let height = getPersonHeight (motehrHeight: 170, fatherHeight: 180, oneIsBoy: 1 );


It is clearer to have external names. You can also abbreviated the External Parameter Name. Suppose we have defined the following functions:

Func getPersonHeight (motherHeight: Float, fatherHieght: Float, oneIsBoy: Int)-> Float


Our local function name is already quite clear. In this case, we only need to add # before it to use it as an external parameter name.

        func getPersonHeight( # motherHeight:Float, # fatherHieght:Float,  # oneIsBoy:Int)  -> Float{                        if oneIsBoy == 1 {                          return  45.99 + 0.78 * (motherHeight+fatherHieght) / 2 + 5.29                        } else {                              return 37.85+0.75 * (motherHeight+fatherHieght) / 2 + 5.29            }                }                let height = getPersonHeight(motherHeight: 170, fatherHieght: 190, oneIsBoy: 1)        println(height)


4. default parameter: for some non-mandatory parameters, we can give them a default value when writing the parameter. The following code sets the default gender to 1.


        func getPersonHeight(motherHeight:Float,fatherHieght:Float, oneIsBoy:Int = 1)  -> Float{                        if oneIsBoy == 1 {                          return  45.99 + 0.78 * (motherHeight+fatherHieght) / 2 + 5.29                        } else {                              return 37.85+0.75 * (motherHeight+fatherHieght) / 2 + 5.29            }                }

When we call it, we will find that the system will add an external name to the parameter with the default value:

Let height = getPersonHeight (170,180, oneIsBoy: 2)

When no value is assigned to a parameter: let height = getPersonHeight (170,180)

Note: default parameters must be placed on the rightmost side of all parameters; otherwise, calling may be confusing.


5. variable parameters: add... after the logarithm type to view the code and calculate the sum of the N integers.

        func sumOfSomeNumbers(numbers:Int...) -> Int {                        var sum: Int = 0                        for item in numbers {                            sum += item            }                    return sum                }             println(sumOfSomeNumbers(1,2,3,4,5))

Note: variable parameters must be placed at the rightmost. If both the default parameters also exist, variable parameters must be placed at the end.

6. input and output parameters:

In swif, parameter passing is a value transfer. Modifications to parameters within the function only occur within the function, and the parameters outside the function are not changed. If you want to change the input parameter, You need to input the output parameter. Such parameter changes within the function will be maintained outside the function. You only need to add inout before the parameter name.

        func inoutTest(var number: Int) {                       number -= 1;        }                var number = 3;                inoutTest(number)                println(number)

The output value is 3.

The following uses the input and output functions. When calling input and output parameters, you must add &

        func inoutTest(inout number: Int) {                       number -= 1;        }                var number = 3;                inoutTest(&number)                println(number)

The output value is 2.

Note: input and output parameters cannot have default values, and variable parameters cannot be used.inoutMark. If you useinoutMark a parameter. This parameter cannot bevarOrletMark.


7. Function Type

In swift, the function belongs to the first type, so it has its own type. The type of the function is determined by the type of the parameter and the type of the returned value.


func addTwoInts(a: Int, b: Int) -> Int {    return a + b}

Var addIntsFunc: (Int, Int)-> (Int) = addTwoInts

 

2. When a function is passed as a parameter, the function type is particularly useful.


        func addTwoNumber(addFunction:(Int,Int)->(Int), number1:Int, number2:Int) ->Int {                                 return addFunction(number1,number2)        }                                func addTwoInt(number1:Int, number2:Int) -> Int {                               return number2 + number1;        }        <pre name="code" class="plain">        func addTwoInt(number1: Int,number2: Int) -> Int {            return number1 + number2;        }        func timesTwoInt(number1: Int,number2: Int) -> Int {            return number1 * number2        }                func chooseStepFunction(isAdd: Bool) -> (Int,Int) -> Int {            return isAdd ? addTwoInt: timesTwoInt;        }                let function:(Int,Int)->(Int) = chooseStepFunction(false)               println(function(1,2))

Println (addTwoNumber (addTwoInt, 1, 2 ));

 

We declare an addTwoNumber function. Its parameter is a (Int, Int)-> (Int) type function and two Int types ., Then, a (Int, Int)-> (Int) type function addTwoInt is defined and used as a parameter.


3. The function is treated as the return value. Now we define a function with a bool value as the parameter, and then return a (Int, Int)-> (Int) function. Code

        func addTwoInt(number1: Int,number2: Int) -> Int {            return number1 + number2;        }        func timesTwoInt(number1: Int,number2: Int) -> Int {            return number1 * number2        }                func chooseCaculateFunction(isAdd: Bool) -> (Int,Int) -> Int {            return isAdd ? addTwoInt: timesTwoInt;        }                let function:(Int,Int)->(Int) = chooseCaculateFunction(false)               println(function(1,2))

ChooseCaculateFunction returns a function that determines whether to return the addTwoInt or timesTwoInt function based on the bool value, and then assigns the constant function. Call this constant to return an Int value and output it.









 


5.



What built-in functions does the swift standard library have?

There are too many new built-in functions in swift. In the basic data type, there are many methods such as Int Double Float String Array, which will not be completed at half past one. Www.cocoachina.com/special/swift/ cocoachina is a good website. You can go to the forum to find a lot of places to talk about swift, as well as the Chinese version of the translated swift pdf.
However, after reading the original book, I thought that although Apple's original book was clear and easy to understand, I did not talk about some new concepts or difficult aspects. Even if you are reading the Chinese version, you will be confused. So
I recommend www.imooc.com. There is a new swift tutorial, which is not very long. It is better to read it after reading it.
 
Basic functions

In mathematics, a function is a relation that maps each element in a set to a unique element in another (possibly the same) set.
(This is only the case where the unary function f (x) = y. Please refer to the general definition in the original English text. Thank you ).
---- A variable so related to another that for each value assumed by one there is a value determined for the other.
The independent variable. A function is a variable associated with a specific volume. Any value of this quantity can find the corresponding fixed value in its quantity.
---- A rule of correspon%between two sets such that there is a unique element in the second set assigned to each element in the first set.
Each element in the first group has a unique corresponding amount in the second group.

The concept of a function is fundamental to every branch of mathematics and mathematics.

Functions

A correspondence in mathematics is the correspondence from A certain set A to A real number set B. To put it simply, as a changes to B, A is the function of B. To be precise, set X to a non-empty set, set Y to a real number set, and set f to a rule, there is a correspondence between Y and y, that is, f is a function on X, and it is recorded as y = f (x), that is, X is the definition field of function f (x, Y is the value range, x is the independent variable, and y is the dependent variable.

Example 1: y = sinx X = [π], Y = [-], which provides a functional relationship. Of course, changing "Y" to "Y1 = (a, B)" and "a <B" to any real number is still a function relation.

The ing between the depth y and the distance x from a shore point O to the measurement point is curved, which represents a function with a definite domain of [0, B 〕. The three examples above show three types of functions: formula, table, and image.
Reference: baike.baidu.com/view/15061.htm1_1

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.