Swift specifically explains the three----------functions (all you want to know here)

Source: Internet
Author: User

function (all you want to know is here)

注:本文为作者自己总结。过于基础的就不再赘述 ,都是亲自測试的结果。如有错误或者遗漏的地方。欢迎指正。一起学习。

1. Simple definition and invocation of functions

The simple no-participation function will not repeat, name is the shape of the participation. Also internally in several names.

func sayHello(name:String) ->String{    return name+" say: hello"}

It's very easy sayHello("zhangsan") to call.
is not very easy ah!

2. External parameter name

What is an external parameter name? The fact is that you have a meaningful nickname for the shape, so that others can understand the purpose of the reference.

func sayHello1(YourNmae name:String,name2:String->String{    return name+" say: hello "+name2}

Add this alias sayHello1(YourNmae: "zhangsan",name2:"lisi") when you call here.
By default, Swift starts with the second parameter and actively adds an external parameter name. equals the internal parameter name.
Suppose you do not want to enter an external parameter name to underline the preceding

add(a:Int , _ b:Int) ->Int{    returna + b}add(11) //2
3. Default value of Parameters

When a function passes in a parameter, it can give a default value, and when the argument is passed, the default value can be passed.

func plus(a:Int,another b:Int=0) -> Int{    return a+b;}

The default value for B here is 0, and the result is 1 when the call is print(plus(1)) received. plus(1,another:2)Get the result is 3

4. Variable number of references

A variable parameter (variadic parameter) can accept one or more values. function is called. You can use variable parameters to pass in an indeterminate number of input parameters. By adding (...) after the variable type name To define a variable number of parameters.

The value of the passed variable parameter is treated as an array of this type in the function body

func arithmeticMean(numbers: Double...) -> Double {    vartotal0    forin numbers {        total += number    }    return total / Double(numbers.count)}

Here numbers is treated as an array to arithmeticMean(1,2,3,4,5.5) get the result 3.1

can also pass a string or whatever other type

... ){    var str = name;    forin  content    {        " "    }    print(str)}

Call say("lily ", content:"like" ,"eat" ,"apple") result: Lily like eat apple

5. Constant parameters and variable parameters

function parameters are constants by default. Attempting to change the value in the function body causes a compilation error

I'm trying to change the value of name here, so I can't change the Let value here.

Sometimes, however, it is useful to assume that a copy of the variable value in the function has an incoming parameter. You can avoid defining a new variable in a function by specifying one or more arguments as a variable parameter. A variable argument is not a constant, and you can use it as a new, modified copy in a function.

That's what we need. Define variable arguments by adding the keyword var before the number of participants:

func say1(var name:String)->String{    "2"    return name;}

Call the function to say1("wangwu") get the result: WANGWU2

6. Function type (functions Types)

What is a function type? In fact, each function has a specific type of function. Consists of the parameter type and return type of the function. For example say1 , the function type above is (String)->string, and () ().

Look at the void in swift, in fact, an empty tuple.

Here's how you can use the function type.

  • function type variable
    var mySay:(String)->String = say1

    Just like defining a normal variable, you can use the function type as a normal type, and here say1 is the function we wrote earlier.
    Of course we can also use Swift's only to judge, not to specify the type var mySay = say1
    The call is the same as calling the normal function mySay("hello") result: Hello2

  • The
  • Function type is used as the parameter type

    func Sayword (Mysay: ( string ) ->  string , Name:string ) ->  string  {return  Mysay (name)}  

    Here we define a function that needs to pass in two of the parameters. The first parameter is a (string)->string of a function type, and finally returns a string. When the
    is called, we can give it a well-defined function Sayword (say1,name: "my") . Result: My2
    We are also able to use closures Sayword ({"\ ($) 2"},name: "my") results: My2
    There are some people who may not be familiar with closures, but don't go into the next section for details.

  • function type as return type

    Sometimes we need to use different functions in different situations, for example, we need to pass in a number. This number is greater than 0 using forward, less than 0 uses backward, of course, here is just simple logic, can be done with if-else, but the logic is very complex can be divided into two functions to write

    Consider the following example:

    func stepForward(input: Int) -> Int {return input + 1}func stepBackward(input: Int) -> Int {    return input - 1}func chooseFunc(distance:Int) -> (Int)->Int{    return distance>10 ? stepBackward:stepForward}

    This defines two very easy functions, or a function that defines a function based on the number of incoming parameters.

    var input = 10;for i in 8...14{    input = chooseFunc(i)(input)    print(input)}

    Here we give the function passed in 8–14, the resulting function is passed in 10. Look at the change in this number. The result: 11 12 13 12 11 10 9 this should be very easy to understand

7. Return to tuple

Our function can also return a tuple type

func minMax( arr:Int ... )->(max:Int,min:Int){    var max = 0    var min = 0    for item in  arr    {        if(item<max)        {            max = item        }        if(item>min)        {            min = item        }    }    return (max,min)}

This is a very easy function, passing in a variable parameter, and then finding the maximum and minimum values in this write.

Invocation: minMax(2,3,5,88,98,-3) Result: (. 0-3,. 1 98)

Optional tuples-Sometimes we return a nil in our function. So this is what we need to write our tuples into an optional tuple.
注意:(Int,Int)?

与 (Int?

,Int?) 不同, (Int,Int)? 表示整个元组是可选的 而不是每一个元素是可选的

func mm()->(max:Int,min:Int)?

{ return nil}if let c = mm(){ print("aa")}else{ print("bb")}

This code finally outputs a BB

8, input and output parameters InOut

Declare the argument of the function as inout this value can be changed in the function, and then replaced by the outgoing function of the original value, so you can not just pass in the literal to the address plus &

var  myDate  =  9func normalFunc(var data:Int){    data = 100}normalFunc(myDate)print(myDate)  //9func inoutFunc(inout data:Int){    data = 100}inoutFunc(&myDate)print(myDate)  //100

As you can see, the normal function does not change the value of the actual participation. and inout back to change. You must add & when passing, in fact, will not add also can explode wrong.

9. Nested functions

You can define functions in other functions called nested functions nested functions are invisible to the outside world.

Or just the few functions that we've been able to play.

func MychooseFunc(distance:Int) -> (Int)->Int{    func stepBackward(input: Int) -> Int {    return input - 1    }    func stepForward(input: Int) -> Int {        return input + 1    }    return distance>10 ? stepBackward:stepForward}

Temporary first so many, later think of what to add, we can collect a dictionary, forget to check the use of methods.

Learning iOS, there is enough for him. Small size brother video. Wisdom, Dark Horse, various swift books

Swift specifically explains the three----------functions (all you want to know here)

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.