"Swift" Closure (Closures)

Source: Internet
Author: User
Tags first string


Closure expressions (Closure Expressions)


Nested functions are a convenient way to name and define self-contained code modules in more complex functions. Of course, it is sometimes useful to write small, non-fully defined and named class function structures, especially if you are working with some functions and need to use other functions as arguments to the function.



A closure expression is a way to construct an inline closure using concise syntax. The closure expression provides some syntax optimizations that make writing closures straightforward. The following example of a closure expression showssort(_:)how the method definition and syntax optimization are represented by using several iterations. Each iteration describes the same functionality in a more concise manner.





Sort functions (the sort function)


The Swift standard library provides a function named tosortsort the values in an array of known types based on the closure function you provide for sorting. Once the sort is complete, thesort(_:)method returns a new array that is the same size as the original array, containing elements of the same type, and the elements are sorted correctly. The original array is not modified by thesort(_:)method.



The following closure expression example usessort(_:)a method to sort an array of type string alphabetically, and the following is the initial array value:


let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]


sort(_:)method requires two parameters to be passed in:


    • Arrays of known types
    • The closure function, which needs to pass in two values that are the same as the array element type, and returns a Boolean value indicating whether the first parameter passed in after the sort ends is preceded or followed by the second argument. If the first parameter value appears before the second parameter value, the sort closure function needs to be returnedtrue, and vice versafalse.


This example sorts anStringarray of one type, so the sort closure function type needs to be(String, String) -> Bool.



One way to provide a sort closure function is to compose a common function that conforms to its type requirements and pass it as a parameter to thessort(_:)method:


func backwards(s1: String, s2: String) -> Bool { return s1 > s2
}
var reversed = names.sort(backwards)
// reversed 为 ["Ewa", "Daniella", "Chris", "Barry", "Alex"]


If the first string (s1) is greater than the second string (s2), thebackwardsfunction returnstrue, indicating that the new arrays1should appears2before. For characters in a string, "greater than" means "appear later in alphabetical order." This means that the letter"B"is larger than"A"the letter and the string is"Tom"larger than the string"Tim". It will be sorted alphabetically, and will be"Barry"ranked"Alex"before.



However, this is a rather lengthy way of essentially simply writing a single-expression function (a > B). In the following example, a closed-expression syntax can be used to better construct an inline sort closure.





Closure expressions Syntax (Closure expression Syntax)


The closure expression syntax has the following general form:


 
{ (parameters) -> returnType in
    statements
}


The closure expression syntax can use constants, variables, andinouttypes as parameters, and does not provide a default value. You can also use variable parameters at the end of the parameter list. Tuples can also be used as parameters and return values.



The following example shows the code for thebackwardsversion of the closure expression that corresponds to the previous function:


 
reversed = names.sort({ (s1: String, s2: String) -> Bool in return s1 > s2
})


It is important to note that inline closure parameters and return value type declarations are thebackwardssame as function type declarations. In both of these ways, it was written(s1: String, s2: String) -> Bool. In an inline closure expression, however, both the function and the return value type are written in curly braces, not outside the curly braces.



The function body part of the closure is introduced by the keywordin. The keyword indicates that the closure parameter and the return value type definition have been completed and the closure function body is about to begin.



Because the function body part of the closure is so short that it can be rewritten into one line of code:


 
reversed = names.sort( { (s1: String, s2: String) -> Bool in return s1 > s2 } )


This means thatsort(_:)the overall invocation of the method remains unchanged, and a pair of parentheses still wraps the entire parameter set in the function. And one of the parameters now becomes an inline closure (compared tobackwardsthe version of the code)


Inferred type based on context (inferring type from context)


Because the sort closure function is passed in as a parameter to asort(_:)method, Swift can infer the type of its parameter and return value. Thesortedsecond parameter is expected to be a function of type(String, String) -> Bool, so in practiceString,StringandBooltypes do not need to be part of the definition of a closure expression. Because all types can be inferred correctly, the return Arrows (->) and the parentheses around the parameters can also be omitted:


 
reversed = names.sort( { s1, s2 in return s1 > s2 } )


In fact, in any case, when a closure constructed with an inline closure expression is passed as a parameter to a function, the parameters and return value types of the closure can be inferred, which means that you hardly need to construct any inline closures with the full format.



However, you can still explicitly write a closed package with a full format. If the full-format closure can improve the readability of your code, you can use a full-format closure. In the case of the method, the purpose of the closure is tosort(_:)sort, and the reader can speculate that the closure is for string processing because the closure is to handle the ordering of the string array.


Single-expression closed Baoyin return (implicit return from Single-expression clossures)


A single-line expression closure canreturnimplicitly return the result of a single-line expression by hiding the keyword, as the previous version of the example can be rewritten as:


 
reversed = names.sort( { s1, s2 in s1 > s2 } )


In this example, thesort(_:)second argument function type of the method is clear that the closure must return aBooltype value. Because the closure function body contains only a single expression (s1 > s2), the expression returns theBoolvalue of the type, so there is no ambiguity and thereturnkeyword can be omitted.





Parameter name abbreviation (shorthand Argument Names)


Swift automatically provides the parameter name abbreviation function for inline functions, which you can call directly, in$0$1$2order to invoke the parameters of the closure.



If you use a parameter name abbreviation in a closure expression, you can omit the definition of it in the closure parameter list, and the type that corresponds to the abbreviation for the parameter name is inferred from the function type.inkeywords can also be omitted, since the closure expression is completely composed of the closure function body:


reversed = names.sort( { $0 > $1 } )


In this example,$0and a$1parameter representing the first and second types in the closureString.








Original source: http://wiki.jikexueyuan.com/project/swift/chapter2/07_Closures.html



"Swift" Closure (Closures)


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.