Today's blog is a comparative basis, or that sentence, the basis of this thing is the most important. When it comes to functions, as long as you've written a program, you know exactly what the function is, and today we'll talk about the features of the functions in swift and the closures in swift. Some of today's small examples are the analogy of the function in Objective-c and so on. There are many useful features in Swift's functions, such as input parameters, using tuples to return multiple values, defining formal parameter names, setting default parameters and variable parameters, and so on. The closure in Swift is the block in Objective-c, and the usage is the same except for the syntax. Cut the crap, start today's topic, get a function in swift, and then engage in a closure in Swift.
I. Functions in Swift
1. Definition and use of functions
Before I introduce the functions in swift, I would like to use a simple addition function in objective-c as a primer, and then analogy the function that implements the same function in Swift. The definition of a function is relatively simple, that is, some grammatical things, the following code fragment is a function of the sum of two integers in OBJC, and returns a sum of two numbers.
-(Nsinteger) SumNumber1: (Nsinteger) number1 number2: (Nsinteger) number2 {return number1 + number2;}
function is relatively simple, that is, two integers are passed in, and then return two integers. The next step is to use the swift language to familiarize yourself with the syntax for defining functions in the swift language. Below is a function that asks for the sum of two integers in the swift language. The syntax is simpler, defining functions in Swift, we use the keyword func to declare the function.
function definition func sum (number1:int, number2:int), int{return number1 + number2;}
The syntax used to describe Swift's definition of basic functions is: func function name (parameter list) , return value type { function body}, so you can define a function. Of course, there are many other uses of function definitions, which are described in more detail below. The above functions are called as follows:
Let Sumtwonubmer = SUM (2, number2:3);
2. List of formal parameters in a function
There is still a need to mention the list of formal parameters in the function, because the parameter list is one of the function data sources, so it is necessary to make a good argument list. The parameter list also has a lot of useful ways to use, and then a detailed description of the function's formal parameter list.
(1) The default parameter is constant (let)
In the formal parameter list of a function, the default parameter is a constant. this is equivalent to using the LET keyword to modify the formal parameters. We can do an experiment, the above addition function to make a modification, in the addition function of the number1 to add 1 operation, you will get an error, the general meaning of this error is "Number1 is not modifiable, because it is a constant of the let type." And the compiler also gives the fix-it (fix) scheme, is to use the var keyword in front of number1 to decorate, make it a variable, so that the value can be modified.
It says so much, a word: formal parameter is a constant, if you want it to be a variable, then you can use the var keyword to decorate, so that the keyword VAR modified variables in the function can be modified. Below is the report of this error, and the compiler provides a solution. (the value of the parameter in the function can be changed by default in OBJC)
(2) Naming parameters
For readability and maintainability of the code, when we define the function, we need a name for each parameter name, so that the caller knows it, it's easy to know what that parameter means. The next step is to modify the addition function in the above, a name for each parameter name, and a look at the method of invocation. Modify the above function, name the first parameter as Numberone, the second parameter is Numbertwo, and the modified function below. The invocation of the sum () function is also changed, and the compiler gives the name of the parameter when the function is called, so the caller is at a glance.
function definition func sum (numberone number1:int, Numbertwo number2:int), int{return number1 + number2;} Let Sumtwonubmer = SUM (numberone:10, numbertwo:20);
When invoking the above function, the compiler gives a hint at a glance.
With regard to the contents of the parameter name in Swift, it is to be noted that at the time of Swift1.0, you can add the # number before the argument, and then the parameter name is the same as the name of the variable (or constant), and the Swift2.0 is removed because the default is equivalent to adding the # number to the Swift1.0.
(3) The function of the transfer to participate in the reference
For the moment, let's say that in a C-language function, you can pass arguments to a function, or the memory address of an incoming argument is called a reference. If a reference is passed in, and the value is modified in the function, then the function, the modified value, can be preserved. It is also possible in swift, but you need to use the InOut keyword to decorate the parameter, and when you use the function, use & to decorate it. This is similar to the C language,& is the address character. Below is a small instance used by InOut.
Func incrementsteptwo (inout mynumber:int) {MyNumber + = 2} var mytestnumber = 6 Incrementsteptow (&mytestnumber) Mytestnumber = 8
After the Mytestnumber variable has passed the Incrementsteptwo () function, its value is increased by 2. Of course, if the mytestnumber is a variable, if Mytestnumber is a constant, then I am sorry, call the function will be error, the following is to change Var to let the IDE after the error prompt. The reason for the error is obviously that you have moved a value that should not be moved, that is, the constant cannot be modified again.
(4) Indefinite parameter function
The number of indeterminate parameter functions is variable, but the type of formal parameter must be the same. How do I take an indeterminate parameter when I use it? An indefinite number of parameters is actually an array, and we can iterate through the values of each parameter in the form of a for loop, and then we can use it. The number of formal parameters of the Incrementmultableadd () function below is variable, and its function is to find multiple integers. In the function we only need to iterate through each parameter, then add each parameter, and finally return the sum we asked for. The function is relatively simple, then it is not verbose.
(5) Default parameter values
In the swift language, it is supported to assign initial values to formal parameters, which is also supported in some other programming languages. But Objective-c's seemingly ancient language does not support specifying an initial value for a parameter, which is supported in Swift's modern programming language. The default parameter specifies a default value for the parameter after the parameter list, or an error occurs. Below is an example of specifying a default parameter for a function's formal parameter. A way to vindicate saylove (), formal parameter youname default is "Ove", the formal parameter lovername is "British Taiwan" by default. followed by the Saylove function of three different calls, in the call function you can not pass parameters, you can pass a parameter, of course, two is not a problem.
Because each parameter of a function has a name, when a function call with a default argument, you can pass a value to any parameter, other parameters take the default value, which is one of Swift's features, see the following simple code example:
3. Function type
Each function has its own type, and the function type is plainly that if the two function argument lists are the same and the return value types are the same, then the two functions have the same function type. In Swift, you can define a variable or constant to store the type of a function. Next you'll use an example and describe what a function type is.
(1) First create two functions with the same function type, one function returns the difference of two integers, and the other function returns the product of two integers. Of course, these two functions are relatively simple, directly on the code:
Now defines two function types with the same function Func diff (Number1:int, number2:int), Int {return number1-number2;} Func Mul (Number1:int, number2:int), Int {return number1 * NUMBER2;}
(2) Once the function is defined, it is then necessary to define an enumeration to enumerate the types of each function, and the following defines the enumeration to be used when selecting a function, which is defined as follows:
Enumeration types that define two kinds of calculations enum Counttype:int {case diffcount = 0 Mulcount}
(3) The next step is to combine the things defined in (1) and (2) by a function. To be blunt, a function is defined to return the function type of the enumeration value by the enumeration value. Sometimes say more easily confused, directly on the code got. The function of the lower function is to return the corresponding function type according to the enumerated value passed in.
Select a function of type and return the corresponding function type func choisecounttype (Counttype:counttype)--(int, int)-int) {//function-type variable var myfunctype :(int, int), int switch CountType {case. Diffcount:myfunctype = diff case. Mulcount:myfunctype = mul} return myfunctype;}
(4) The next step is to use the function defined in (3), and first we need to define a variable of the corresponding function type (int, int) and int) to receive the Choisecounttype () The function type is returned in the function, and then the function type variable is called, and the results are executed in playground:
4. Function nesting
We can rewrite the code in 3 using function nesting, which supports nested functions in swift. So let's put the functions in 3.1 and 3.2 into the 3.3 function, so we can rewrite the above code using function nesting. Using a function to nest the rewritten code is as follows, of course, the invocation of the Choisecounttype () function does not change, and the rewritten invocation method is the same as in 3.4.
Select a function of type and return the corresponding function type Func choisecounttype (Counttype:counttype) -> ((int, int) -> int) { //now defines two functions of the same function type func diff (Number1:int, number2:int) -> Int { return number1 - number2; } func mul (Number1:int, number2:int) -> Int { return number1 * number2; } //function type variable var myfunctype: (Int, Int) -> Int switch countType { case . Diffcount: myfunctype = diff case . mulcount: myfunctype = mul } return myfunctype;}
Two. Closures
Said the closure in Swift, have to mention is the block in the objective-c, in fact, the two is a thing, use and use the scene are the same. We can simply introduce the Closure (closure) in Swift by analogy to the block in Objective-c. is actually an anonymous function. In the next section, let's start with the basic syntax of closure in Swift, and then spy on closure's usage scenarios in analogy with the block in OBJC.
Declaration of 1.Closure variables
Closure is an anonymous function, we can define a closure variable, and the type of the closure variable is the "function type" we described above. Defining a closure variable is actually a variable that defines a particular function type, in the following way. Because the closure variable does not have an initial value assigned to it, we declare it as a variable of an optional type. When in use, use! Force to open.
var myCloure0: ((int, int), int)?
In addition to the above approach, we also use another common way of declaring closure variables. That is to use the keyword Typealias to define a specific function type, we can take this type to declare a closure variable, as shown below
Defines the closure type (that is, a function type) Typealias Myclosuretype = (int, int), int var mycloure:myclosuretype?
2. Assigning values to closure variables
Assigning a value to a closure variable is actually a variable that assigns a function body to a function type, and the definition of the function is not very different. But the function body that assigns a value to a closure variable contains a list of parameters, and the argument list and the real function body are separated by the keyword in. The closure optional variable is called in the same way as the normal function, the only difference is that the function needs to be opened to be used. The assignment and invocation are as follows.
3. Application example of closure callback
For the moment, it is called the closure callback, which is actually the block callback in OBJC. The closure callback in Swift is consistent with the block callback usage in OBJC, and one example of closure application is presented below. A two view controller is created below, which we will call Firstviewcontroller and Secondviewcontroller. There is a label and a button on the Firstviewcontroller, this button is used to jump to Secondviewcontroller, This label is used to display values that are recalled from Secondviewcontroller. And Secondviewcontroller also has a textfield and a button, Clicking the button will return the value in the input box to the Firstviewcontroller and then to the label on the Firstviewcontroller.
(1) The first step in building this example is to use Stroyboard to lay out the controls we need and to manage the appropriate classes. Of course, the focus of our demo is not how to layout the control, how to relate to the control, and how to use the control, so the above does not repeat. The focus of this example is how to use closure to implement a callback for a value. Below is our control layout and directory structure, from the controls on the storyboard, the function is also at a glance. Click on the "Go Secondviewcontroller" button on "Firstviewcontroller" and you will be redirected to "Secondviewcontroller". Enter a value in the input box on the Secondviewcontroller view and click the Back button to return to Firstviewcontroller, At the same time, the text in the input box is returned in the form of a closure callback to be displayed on the Fristviewcontroller label. Roughly on this simple function.
(2) content in Firstviewcontroller.swift
Firstviewcontroller.swift in the content is relatively simple, associated with a label control and a button click on the event, click the button will jump to Secondviewcontroller, the specific code is as follows, this is not verbose, see the code in the comments. The important point of the code below is to implement the closure callback provided when jumping to secondviewcontroller in order to accept the returned value.
FirstViewController.swift// SwiftDemo//// Created by MR.LUDASHI ON 15/11/18.//  COPYRIGHT ? 2015 year zeluli. all rights reserved.//import UIKitclass FirstViewController: UIViewController { @IBOutlet var showtextlabel: uilabel! // Display the callback text message override func viewdidload () { super.viewdidload () } Override func didreceivememorywarning () { Super.didreceivememorywarning () } // Click the button to jump to secondviewcontroller @IBAction func tapgosecondviewcontrollerbutton ( Sender: uibutton) { //loading from Storyboard secondviewcontroller let secondvc = uistoryboard (name: "Main", bundle: Nsbundle.mainbundle ()). Instantiateviewcontrollerwithidentifier ("Secondviewcontroller") as! secondviewcontroller The //implements the callback and receives the callback value secondVC.setBackMyClosure { ( inputtext:string) -> Void in self.showtextlabel.text = inputtext } // Push to Secondviewcontroller self.navigationcontroller?. Pushviewcontroller (secondvc, animated: true) &nbsP;}}
(3) content in Secondviewcontroller.swift
The content in Secondviewcontroller.swift is also not troublesome, except that the associated controls and events define a closure type (function type) and then declare a variable of this function type using this particular function type. We can use this variable to accept the closure of the previous page, so that the user input values, through the closure of the body back to the previous page. The specific code is implemented as follows:
SecondViewController.swift// SwiftDemo//// Created by MR.LUDASHI ON 15/11/18.//  COPYRIGHT ? 2015 year zeluli. all rights reserved.//import UIKittypealias InputClosureType = (String) -> void //defines a closure type (a specific function type function type) class secondviewcontroller: uiviewcontroller { @IBOutlet var inputTextField: UITextField! //input box, let the user enter a value, and then through the closure callback to the previous page var backclosure:i nputclosuretype? //receive the last page through the closed block override func viewdidload () { super.viewdidload () } override func Didreceivememorywarning ()  { &NBsp; super.didreceivememorywarning () } Seter method for //closure variables func setbackmyclosure ( Tempclosure:inputclosuretype) { self.backclosure = tempClosure } @IBAction func tapbackbutton (Sender: uibutton) { if self.backclosure != nil { let tempString:String? = self.inputTextField.text if tempString != nil { self.backclosure! (tempstring!) } } self.navigationcontroller!. Popviewcontrolleranimated (True) }}
(4) After the above steps This example has been completed, the next step is to look at the time of the effect of the operation. Originally want to make git dynamic diagram, feel the instance function is simple, and the UI is also relatively simple, did not do, or see it. The effect of the operation is as follows:
4. Closure functions commonly used in arrays
Some of the more useful closure functions are brought in the swift array, such as map, Filter, and Reduce. Then take a good look at these closures, it is still relatively cool to use.
(1) Map (map)
When it comes to the use and functionality of maps, it is not a strange way to use the map in the sequence if you have used the REACTIVECOCOA framework. In fact, the use of the two methods and functions are very similar. It doesn't matter if you haven't used a map from a RAC, so let's take a look at the map closure function in the array first.
With the above code snippet and running result, it is not difficult to see that the function of the map closure function is to iterate through each item in the array, and then process each item in the array with the mapping rule, and the resulting return is the processed one (in the form of a new array). Of course, the value of the element in the original array remains constant, which is the use and function of the map closure function.
(2) filter (filter)
The use of filter is better understood, filter is a colander, is used to filter the data that meets the criteria. The sequence in Reactivecocoa also has filter, and the usage is to filter the data in the sequence. The filter in the array is used to filter the data in the array and returns the new array, and the new array holds the data that matches the criteria. The use of the filter is as follows, the example below is a height filter, filter out the height of less than 173 people, return is greater than or equal to 173 of the height data.
(3) Reduce
There is also the concept of reduce in Reactivecocoa, where reduce is used to combine the reduction of the signal Reactivecocoa. Use the reduce closure function in the swift array to merge items and the merged value. The example below is an array of salary, which holds the monthly salary. We're going to use the reduce closure function to calculate the total salary. Below is the demo:
A case study of Swift's function and closure