Getting Started with Swift functions

Source: Internet
Author: User
Tags types of functions

1. Functions in Swift are the first type, so functions can also be used as parameters and return results


2. Define the form keyword name (parameter list) and return value type. The following is an example of returning a tuple.

        Func Addnumber (A:int,b:int)-(Addresult:int, timesresult:int) {                        return (a+b, a*b)                } let                result =  A Ddnumber (1, 2)                println (Result.addresult)
Pass in two parameters a, B and add them together, and the result of multiplying is returned in the form of a tuple. There can be no arguments, but there must be () that represents the parameter, and the,-> to {before the return value is omitted. The absence of a return value here means that we do not define a return value, but the function actually returns a void value. It is actually an empty tuple, without any elements that can be written ()


3. Parameter name of the function:

As we see above in the form of the function, the parameter name A, B is only a local variable, we can only use within the function of our own definition, cannot be used externally.

Assuming that a function has multiple parameters, we may not know the explicit meaning of these parameters when we use them. At this point we can use the external parameter name to solve the problem.

Now there is a function that requires the passing of three functions, the height of the parents and the number of men and women 1 and two to ask for the height of their children. 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 prompt for the meaning of these three numbers, which can cause errors in the value of the pass.  Now we only need to use the external names of the parameters, and we can explicitly indicate what they mean when they are called. The external name of the parameter is prepended to the local name and opened with a space.


                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 the call does not have an external name

Let height = getpersonheight(1) ;

When calling code that has an external name

Let height = getpersonheight(motehrheight:fatherheight: oneisboy: 1 );


Having an external name is more clear. And we can abbreviate the external parameter names. If we have defined the following function

func getpersonheight (motherheight:float, fatherhieght:float, Oneisboy:Int)- >Float


Our local function name is already quite clear, and we just need to precede it with #, which can be used 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 * (motherhe Ight+fatherhieght)/2 + 5.29            }                } let                height = getpersonheight (motherheight:170, fatherhieght:190, Oneisbo y:1)        println (height)


4. Default parameters: For some parameters that do not have to be assigned, we can give them a default value when we write parameters. The following code gives the gender default of 1


        Func getpersonheight (motherheight:float,fatherhieght:float, oneisboy:int = 1),  float{                        if Oneisboy = = 1 { C3/>return  45.99 + 0.78 * (motherheight+fatherhieght)/2 + 5.29                        } else {                              return 37.85+0.75 * (MOTHERHEIGHT+FA Therhieght)/2 + 5.29            }                }

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

let height = Getpersonheight ( 170 180 )   

When you do not assign a value to a parameter: let height = getpersonheight(in.

Note: The default parameter must be placed at the far right of all parameters, otherwise it will cause the call to be confusing.


5. Variable parameter: Add after logarithmic type ... Look directly at the code to find N integers and

        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: The variable parameter must be on the rightmost side, and when the default parameter also exists, the variable parameter is placed last.

6. Input and OUTPUT parameters:

The passing of parameters in Swif is a value pass, and the modification of parameters within the function only occurs inside the function, and the outside parameters of the function are not changed. If you want to change the parameters passed in, we need to input the output parameters, so that the parameters within the function of the change that will remain outside the function. The input output only needs to be preceded by the parameter name with InOut.

        Func Inouttest (var number:int) {number-                       = 1;        }                var number = 3;                Inouttest (number)                println (number)

The value of the output is 3

The input and output functions are used below, and the input and output parameters are called with & in front of the parameters.

        Func inouttest (inout number:int) {number-                       = 1;        }                var number = 3;                Inouttest (&number)                println (number)

the value of the output is 2

Note: input and output parameters cannot have default values, and mutable parameters cannot be used inout tags. If you inout mark a parameter, this parameter cannot be var or be let marked.


7. Types of functions

In Swift, a function is of the first type, so it has its own type, and the type of the function is determined by the type of the parameter and the type of the return value.


Func addtwoints (A:int, b:int), Int {    return a + b}

    1. The type of this function is (int,int), (Int). We can define this type of variable

var Addintsfunc: (Int,int)-(Int) = Addtwoints

2. Functions are passed as arguments, and the type of the function 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 + numb Er2;        }        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 ())

println (Addtwonumber (Addtwoint,));


We declare a addtwonumber function whose argument is a (int,int)-(int)-type function and a number of two Int types. , and then define a(Int,int)-type (Int) function Addtwoint function is then used as a parameter.


3. The function is treated as a return value. We now define a function that takes a bool value as an argument and then returns a function (Int,int), (INT). 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 ())

Choosecaculatefunction returns a function that, depending on the bool value, returns the Addtwoint or Timestwoint function and assigns a constant function. Call this constant to return an int value and output.










5.


Getting Started with Swift 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.