Apple new programming language Swift language advanced (vi)--functions and closures

Source: Internet
Author: User
Tags closure definition
<span id="Label3"></p><p><p>http://blog.csdn.net/goohong/article/details/31411591</p></p><p><p>first, the function</p></p><p><p>1.1. definition and invocation of functions</p></p><p><p>The function is defined with the Func keyword as the prefix, followed by the function name, followed by a parenthesis that can have parameters or without parameters, followed by the return type of the Function. The function execution body is surrounded by a pair of curly braces {}. A function named SayHello is defined as follows, which contains an input parameter named personname, which is of type string.</p></p> <blockquote> <blockquote> <p>Func SayHello (personname:string), String {</p> <p>Let greeting = "Hello," +personname + "!"</p> <p>return greeting</p> <p>}</p> </blockquote> </blockquote><p><p>You can call this function by using the function name SayHello defined above and enclosing a string parameter value to the function in Parentheses. For example</p></p><p><p>SayHello ("Anna").</p></p><p><p></p></p><p><p>Swift can also define a function without a return value, such as</p></p> <blockquote> <blockquote> <p>Func Saygoodbye (personname:string) {</p> <p>println ("goodbye,\ (personname)!")</p> <p>}</p> </blockquote> </blockquote><p><p>Note: The return type of the function that does not define the return value is void, which is an empty multivariate group (containing 0 elements), written ().</p></p><p><p>A multivariate group type can be used as the return type of a function in Swift to return multiple values from a Function.</p></p> <blockquote> <blockquote> <p>Func Count (string:string), (vowels:int,consonants:int,others:int) {</p> <p>Return (vowels,consonants,others)</p> <p>}</p> </blockquote> </blockquote><p><p>The parameters in the functions defined above are defined as Parametername:parametertype in parentheses, and the parameters defined in this form are called local parameters, which can only be used inside the Function's body and cannot be used when a function is Called.</p></p><p><p>Swift supports naming an external parameter for each parameter of a function, and the external parameter is declared before the Function's local parameter. As shown Below:</p></p> <blockquote> <blockquote> <p>Func join (string s1:string,tostring s2:string,withjoiner Joiner:string)</p> <p>->string {</p> <p>return S1 +joiner +s2</p> <p>}</p> </blockquote> </blockquote><p><p>External parameters that are named for a function can be used only when the function is Called. The above function is called as shown below with the name of the external parameter named after the Parameter.</p></p><p><p>Join (string: "hello", toString: "world", withjoiner: ",")</p></p><p><p>Naming an external parameter for a function parameter is primarily intended to make the Function's parameter meaning Clearer.</p></p><p><p>If a Function's local parameter name is already appropriate, you can precede the Function's local parameter name with a ' # ' symbol, indicating that the parameter name is used as the local parameter name and for the external parameter Name. Such as:</p></p> <blockquote> <blockquote> <p>Func containscharacter (#string: string, #characterToFind: Character)->bool {</p> <p> </p> <p>}</p> </blockquote> </blockquote><p><p>In swift, you can also define a default value for any parameter of a function in a function definition. If you provide a default value for a parameter of a function, you can call the function without passing the parameter that defines the default Value.</p></p><p><p>Parameters that define default values are placed at the end of the function argument list, and parameters that do not have default values are placed in front of the function argument list so that the calling function is uniform in form.</p></p><p><p></p></p> <blockquote> <blockquote> <p>Fund Join (string S1:string,tostring s2:string,</p> <p>Withjoiner joiner:string = "")->string {</p> <p>return S1 +joiner +s2</p> <p>}</p> </blockquote> </blockquote><p><p>The join function above defines the default parameters for the joiner parameter, so the function can be called as follows, the third parameter is not passed, and the function uses its default value internally:</p></p><p><p>Join (string: "hello", toString: "world")</p></p><p><p>Returns "hello world"</p></p><p><p>In most cases it is necessary and useful to provide an external name for a parameter with a default value so that the function can be expressed more clearly when the function is Called.</p></p><p><p>therefore, in this case, if you do not provide an external name for the default parameter, swift automatically assigns it an external parameter name, and the automatically assigned external parameter name is the same as its local name. Here's an example:</p></p> <blockquote> <blockquote> <p>Func Join (s1:string,s2:string,joiner:string = "")->string {</p> <p>return S1 +joiner +s2</p> <p>}</p> </blockquote> </blockquote><p><p>As above function Swift automatically provides an external parameter name for the joiner parameter with the default value, whose name is the same as its local name Joiner.</p></p><p><p>The function must therefore be called with an external name, so that the meaning of the expression of the function parameter is clearer and unambiguous.</p></p><p><p>Join ("hello", "world", joiner: "-")</p></p><p><p>Swift also supports functions with variable parameters to accept 0 or more specific types of parameters. Variable parameters are added after the parameter type ... Symbol Identification. The variable arguments passed to the function are used in the body of the function as an array of the appropriate type.</p></p><p><p>The following example shows an example of a function that uses variable Parameters.</p></p> <blockquote> <blockquote> <p>Func Arithmeticmean (numbers:double ...), Double {</p> <p>var total:double =0</p> <p>For number in numbers {</p> <p>Total +=number</p> <p>}</p> <p>return total/double (numbers.count)</p> <p>}</p> </blockquote> </blockquote><p><p>To avoid ambiguity, the Function's mutable parameters always appear at the end of the function argument List.</p></p><p><p>function parameters are constant types by default and do not require a let flag. however, Swift supports the use of the var keyword in function definitions to define variable parameters, and variable parameters are only valid and used within the Function's execution Body.</p></p> <blockquote> <blockquote> <p>Func alignright (var string:string,count:int,pad:character)->string {</p> <p>Let Amounttopad =count-countelements (string)</p> <p>For _ in 1 ... amounttopad {</p> <p>String =pad +string</p> <p>}</p> <p>return string</p> <p>}</p> </blockquote> </blockquote><p><p>Swift in order to support the value of the parameter modification within a function body can still be used externally after the function call, defines a in-out parameter.</p></p><p><p>Swift adds a inout keyword in front of the parameter definition to define a in-out parameter. The In-out parameter allows you to modify the values passed in within the function and return them instead of the original Values. Since the In-out parameter is used as a variable, you need to put a & tag in front of its name to indicate that the parameter is a in-out parameter inside a function that can be modified and passed back to the Value.</p></p><p><p>It is important to note that the In-out parameter cannot have no default value, the mutable parameter cannot be marked as a inout parameter, or it cannot be marked with the Var or let Keyword.</p></p> <blockquote> <blockquote> <p>Func swaptwoints (inout a:int,inout B:int) {</p> <p>Let Temporarya =a</p> <p>A =b</p> <p>b =temporarya</p> <p>}</p> </blockquote> </blockquote><p><p>The Swaptwoints function above defines two inout parameters for the exchange of two parameter values within a Function. You can call the function in the following ways:</p></p> <blockquote> <blockquote> <p>var someint =3</p> <p>var anotherint =107</p> <p>Swaptwoints (&someint, &anotherint)</p> </blockquote> </blockquote><p><p>1.2. function type and use</p></p><p><p>Each function belongs to a specific type of function, and the function type consists of the type of the parameter and the return type of the Function.</p></p> <blockquote> <blockquote> <p>Func addtwoints (a:int,b:int)->int {</p> <p>Return a +b</p> <p>}</p> <p>Func multiplytwoints (a:int,b:int)->int {</p> <p>Return a *b</p> <p>}</p> </blockquote> </blockquote><p><p>For example, the two functions defined above are of the same function type and are of Type: (int, int), int.</p></p><p><p>In swift, you can use a function type like any other type (a function type is a reference type), such as defining a constant or variable as a function type and assigning it an appropriate Function.</p></p><p><p>Let Anothermathfunction =addtwoints</p></p><p><p>Anothermathfunction is inferred to be a type (int, int), int Function.</p></p><p><p></p></p><p><p>You can also use a function type as a parameter to another Function. As shown Below:</p></p> <blockquote> <blockquote> <p>Func printmathresult (mathfunction: (int,int)->int, a:int, B:int) {</p> <p>println ("result:\ (mathfunction (b))")</p> <p>}</p> </blockquote> </blockquote><p><p>Printmathresult (addtwoints,3,5)</p></p><p><p>You can also use a function type as a return type for another function, such as:</p></p> <blockquote> <blockquote> <p>Func Stepforward (input:int)->int {</p> <p>return input +1</p> <p>}</p> <p>Func Stepbackward (input:int)->int {</p> <p>Return input-1</p> <p>}</p> </blockquote> </blockquote><p><p>The above defines two functions with the same type.</p></p> <blockquote> <blockquote> <p>Func choosestepfunction (backwards:bool)-(Int)->int {</p> <p>return backwards? Stepbackward:stepforward</p> <p>}</p> </blockquote> </blockquote><p><p>The function returns different functions based on the different values of the Parameters.</p></p><p><p>var currentvalue =3</p></p> <blockquote> <blockquote> <p>Let Movenearertozero =choosestepfunction (currentvalue >0)</p> </blockquote> </blockquote><p><p>CurrentValue =movenearertozero (currentvalue)</p></p><p><p></p></p><p><p>1.3. Nesting of functions</p></p><p><p>In swift, other functions can be defined in the body of the function, called function nesting, functions defined inside a function are called nested functions, and the outermost defined functions are collectively referred to as global functions. Nested functions are hidden from the outside by Default. Can only be called or used within the function that defines it. But a function that contains a nested function can return the nested functions it contains so that the nested function can be used EXTERNALLY. As shown Below:</p></p> <blockquote> <blockquote> <p>Func choosestepfunction (backwards:bool)-(Int)->int {</p> <p>Func stepforward (input:int)->int {return input +1}</p> <p>Func stepbackward (input:int)->int {return input-1}</p> <p>return backwards? Stepbackward:stepforward</p> <p>}</p> <p>The above function Choosestepfunction internally defines two inline functions and returns one of the two inline functions based on the values passed in the Parameter.</p> </blockquote> </blockquote><p><p>Two closures (Closures)</p></p><p><p>2.1 Closure Definition</p></p><p><p>A closure is a self-contained function block that can be used like a function, and closures are similar to blocks (blocks) defined in the C and Objective-c Languages.</p></p><p><p>A closure, like a function, is also a type (reference type), can also be assigned a closure to a constant or variable, and in fact the constant or variable points to a reference to that Closure.</p></p><p><p></p></p><p><p>global functions and nested functions are special cases of closures. The closure in Swift refers to one of the following three forms:</p></p><p><p>1) Global function, global function can not capture any value;</p></p><p><p>2) nested functions, Nested functions can capture values from the functions that define them;</p></p><p><p>3) The closure expression is a closed packet with no name, is a lightweight syntax for implementing closures, and a closure expression can capture values from their usage context.</p></p><p><p>The syntactic form of a closure expression is:</p></p> <blockquote> <blockquote> <p>{(parameters), return type in</p> <p>Statements</p> <p>}</p> </blockquote> </blockquote><p><p>The main difference between a closure expression and a function is that the closure expression has no function name. The contents of the entire closure expression are enclosed in a pair of curly braces, and the arguments and return types of the closure expression are also declared inside the braces, and the In keyword is used to elicit the execution of the closure Expression.</p></p><p><p>A closure expression, like a function, can also use a constant parameter, a variable argument, or a inout parameter, or a variable parameter, but different places cannot provide a default value for the parameters of a closure Expression.</p></p><p><p>The following is an example of using a closure expression in inline Mode.</p></p><p><p>Reversed = sort (names, {(s1:string, s2:string), Bool in return s1 > S2})</p></p><p><p>2.2 Optimization of closure expressions</p></p><p><p>When a closure is delivered to a function in an inline closure expression, the parameters and types of the closure expression can be inferred from the parameters of the function, as</p></p><p><p>The sorting closure above is passed and used as the second parameter of the sort function, and swift can infer the type of the Closure's parameter type and the return type (string, string), type bool, from the second parameter of the sort Function.</p></p><p><p>therefore, in this case, the parameters and return types of the closure expression are rarely required to be declared in the actual code, and can be simplified to the following form:</p></p><p><p>Reversed =sort (names, {s1,s2 in return s1 >s2})</p></p><p><p>In swift, a single-expression closure can implicitly return the results of the expression, so the return keyword above can be omitted.</p></p><p><p>Reversed = sort (names, {s1, s2 in S1 > S2})</p></p><p><p>Swift can automatically provide shorthand names for the parameters of an inline closure expression, use the form $0,$1,$2, and so on to define and reference the parameter values contained in the closure Expression. The argument list of the inline closure expression can also be canceled, when the closure expression contains only one executor, so the In keyword can also be omitted.</p></p><p><p>In this way, the sort function with the inline closure expression above can be optimized to the following simplest form:</p></p><p><p>Reversed =sort (names, {$ >$1})</p></p><p><p>Because the string type implements a string manipulation function with a > operator (greater than). The function type of the action function matches the type of function required by the second parameter of the sort function, so you can simply transfer a > operator in the above function, and Swift will help you infer the string implementation that you want to use it. So the above expression can also be written as Follows:</p></p><p><p>Reversed =sort (names, >)</p></p><p><p>If a closure expression is passed as the last parameter of a function, and the closure expression is too long. Closures can also be used to postpone the FORM.</p></p><p><p>Closure delay refers to a closure expression that is written outside the argument brackets of the function it supports when the function is Called.</p></p><p><p>As a result, as above, the sort function can be called in the following form, which makes the code more Readable.</p></p><p><p>Reversed = sort (names) {$ > $}</p></p><p><p>If a closure expression is the only parameter of a function and is expressed as a closure, the function contains parameters () that can be omitted when the function is Called. As shown in the following example:</p></p> <blockquote> <blockquote> <p>Let strings =numbers.map {</p> <p>(var number)->string in</p> <p>var output = ""</p> <p>While number >0 {</p> <p>Output =digitnames[number%10]! +output</p> <p>number/=10</p> <p>}</p> <p>Return output</p> <p>}</p> </blockquote> </blockquote><p><p>Capture of 2.3 values</p></p><p><p>Closures can capture references and assign values to arbitrary constants or variables from the context in which they are defined.</p></p><p><p>A closure can capture a constant or variable from its defined context, and then reference or modify the captured constant or variable in its execution, even if the definition of a constant or variable is no longer valid.</p></p><p><p>A nested function can capture parameters, arbitrary constants, or variables from parameters and external functions that define its external functions.</p></p> <blockquote> <blockquote> <p>Func makeincrementor (forincrement amount:int), ()->int {</p> <p>var runningtotal =0</p> <p>Func incrementor ()->int {</p> <p>RunningTotal +=amount</p> <p>Return RunningTotal</p> <p>}</p> <p>Return Incrementor</p> <p>}</p> </blockquote> </blockquote><p><p>In the example above, Makeincrementor's inline function Incrementor captures a variable and a parameter from its defined function Makeincrementor. Because the captured parameters are not modified inside the nested function body, they are captured as copies of the original Values. The captured variable needs to be modified inside the inline function, so the inline function captures a reference to the original variable, capturing a reference to ensure that the reference continues to work after the external function call that defines the inline function, which is handled automatically by swift, and that the user does not need any Action.</p></p><p><p>The following example shows each call to an inline function, and the reference value is modified on the original basis, although the external function Makeincrementor call has Ended.</p></p><p><p>Let Incrementbyten = Makeincrementor (forincrement:10)</p></p> <blockquote> <blockquote> <p>Incrementbyten ()</p> <p>Returns a value of 10</p> <p>Incrementbyten ()</p> <p>Returns a value of 20</p> <p>Incrementbyten ()</p> <p>Returns a value of 30</p> </blockquote> </blockquote><p><p></p></p><p><p>All rights reserved, Please clearly indicate the link and the source when reproduced, thank you!</p></p><p><p>Copyright Notice: This article for Bo Master original article, without Bo Master permission not Reproduced.</p></p><p><p>Apple new programming language Swift language advanced (vi)--functions and closures</p></p></span>

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.