Swift Closure (vi)

Source: Internet
Author: User
Tags vars

http://blog.csdn.net/huangchentao/article/details/32714185

Closed Bag Closures

1. Closed-Packet expressions

A closure expression is a way of building an inline package with simple syntax that provides some syntax optimizations that make the closure code more straightforward

1.1sort function

The SWIFT Standard library provides the sort function to sort the values in an array of known types, returning an array that is equal to the original array size but whose elements are sorted correctly
The sort function requires the passing of two parameters:
1. Arrays of known types
2. Pass in two closure functions with the same type parameters as the array and return a Boolean value that tells the sort function whether the first parameter passed in before or after the end of the second parameter, if the first parameter value appears before the second parameter value, the sort closure function needs to return true, otherwise it returns false

[OBJC]View Plaincopy
    1. Let names = ["Chris", "Alex", " Ewa", "Barry", "Daniella"]

This example sorts an array of type string, so the sort closure function type is (string, string), Bool
Another way to provide a sort closure function is to write a normal function that meets its type requirements and pass it as the second argument to the sort function.

[OBJC]View Plaincopy
    1. Func backwards (S1:string, s2:string), Bool {
    2. return s1 > S2
    3. }
    4. var reversed = sort (names, backwards)
    5. Reversed is equal to ["Ewa", "Daniella", "Chris", "Barry", "Alex"]
1.2 Closure-expression syntax

The general form of a closure expression, you can use constants, variables, and inout types as parameters, do not provide default values, or you can use variable arguments after the parameter list. Tuples can also be used as parameters and return values

[OBJC]View Plaincopy
  1. {(parameters), return type in
  2. Statements
  3. }
  4. The backwards function corresponds to the closure expression version, and the function body part of the closure is introduced by the keyword in
  5. The keyword indicates that the closure parameter and the return value type definition have been completed, and the closure function body begins
  6. Reversed = sort (names, {(S1:string, s2:string), Bool in
  7. return s1 > S2
  8. })
  9. Shorthand form
  10. Reversed = sort (names, {(S1:string, s2:string), Bool in return s1 > S2})
1.3 Inferred types based on context

Because the sort closure function is passed in as a parameter to the sort function, Swift can determine the type of its parameter and return value

[OBJC]View Plaincopy
    1. Reversed = sort (names, {s1, S2 in return s1 > S2})
1.4 Single-line expression closed Baoyin return

Single-line expression closure can implicitly return the result of a single-line expression by hiding the return keyword

[OBJC]View Plaincopy
    1. Reversed = sort (names, {s1, S2 in S1 > S2})
1.5 parameter name abbreviation

Swift automatically provides parameter name abbreviations for inline functions, which can be used to sequentially invoke closure parameters directly through $0,$1,$2. 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. The In keyword can also be omitted, since the closure expression is completely composed of the closure function body

[OBJC]View Plaincopy
    1. Reversed = sort (names, {$0 > $1})
1.6 Operator functions

Swift's string type defines an implementation of the strings for the greater-than sign (>), which takes two arguments of type string as a function and returns a value of type bool. This coincides with the type of function that the second parameter of the sort function requires. So you can simply pass a greater-than sign, and Swift can automatically infer that you want to use a string function greater than the number to implement

[OBJC]View Plaincopy
    1. Reversed = sort (names, >)
2. Trailing closures

If you need to pass a long closure expression as the last argument to a function, you can use a trailing closure to enhance the readability of the function. If a function needs only one parameter of the closure expression, it can even omit () when the trailing closure is used.

[OBJC]View Plaincopy
  1. Func somefunctionthattakesaclosure (Closure: ()) {
  2. //function body goes here
  3. }
  4. The following is a function call that does not use a trailing closure
  5. Somefunctionthattakesaclosure ({
  6. //closure ' s body goes here
  7. })
  8. The following is a function call using a trailing closure
  9. Somefunctionthattakesaclosure () {
  10. //Trailing closure ' s body goes here
  11. }
  12. In the example above, the string sorting as the sort function parameter can be rewritten as:
  13. Reversed = sort (names) {$0 > $1}
  14. Let digitnames = [
  15. 0: "Zero", 1: "One", 2: "One", 3: "Three", 4: "Four" ,
  16. 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"
  17. ]
  18. Let numbers = [16, 58, 510]
  19. Let strings = numbers. map {
  20. (var number), String in
  21. var output = ""
  22. While number > 0 {
  23. Output = digitnames[number% 10]! + output
  24. Number/= 10
  25. }
  26. return Output
  27. }
  28. Strings is inferred to be of type string[]
  29. Its value is ["Onesix", "Fiveeight", "Fiveonezero"]

3. Value capture

Closures can capture constants or variables in the context in which they are defined. Even though the original domain that defines these constants and variables does not already exist, closures can still reference and modify these values in the closure function body. Swift's simplest form of closure is a nested function, which is a function defined in the function body of another function. A nested function captures all parameters of its outer function, as well as the constants and variables defined.

[OBJC]View Plaincopy
  1. Func makeincrementor (forincrement amount:int), Int {
  2. var runningtotal = 0
  3. Func incrementor (), Int {
  4. RunningTotal + = Amount
  5. return runningtotal
  6. }
  7. return Incrementor
  8. }
  9. Func incrementor (), Int {
  10. RunningTotal + = Amount
  11. return runningtotal
  12. }
  13. Let Incrementbyten = Makeincrementor (forincrement: 10)
  14. Incrementbyten ()
  15. Returns a value of 10
  16. Incrementbyten ()
  17. Returns a value of 20
  18. Incrementbyten ()
  19. Returns a value of 30
  20. Let Incrementbyseven = Makeincrementor (forincrement: 7)
  21. Incrementbyseven ()
  22. Returns a value of 7
  23. Incrementbyten ()
  24. Returns a value of 40

4. Closures are reference types

Whether assigning a function/closure to a constant or a variable, the actual value of the constant/variable is set to the corresponding function/closure reference, and if the closure is assigned to two different constants/variables, two values will point to the same closure

[OBJC]View Plaincopy
    1. Let Alsoincrementbyten = Incrementbyten
    2. Alsoincrementbyten ()
    3. Returns a value of 50

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Swift Closure (vi)

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.