Swift Learning 14: Closures (Closures)

Source: Internet
Author: User
Tags closure vars

  1. * Closures (Closures)
  2. * Closures are self-contained functional code blocks that can be used in code or used as parameters to pass values.
  3. * Closures in Swift are similar to the lambdas in C, OC, and other programming languages such as Python (blocks).
  4. * Closures can capture and store references to any constants and variables defined in the context. This is called the self-containment of variables and variables,
  5. * Hence the name "closure" ("Closures)"). Swift also handles memory management for all captured references.
  6. *
  7. * Global functions and nested functions are really special closures.
  8. * Closures in the form of:
  9. * (1) Global functions are closures, have names but cannot capture any values.
  10. * (2) Nested functions are closures and have names that can also capture values within the enclosing function.
  11. * (3) The closure expressions are anonymous closures, which use lightweight syntax to capture values based on the context environment.
  12. *
  13. * Closures in Swift have a lot of optimizations in place:
  14. * (1) Infer parameters and return value types based on context
  15. * (2) Implicit return from a single-line expression closure (that is, the closure body has only one line of code, you can omit return)
  16. * (3) You can use simplified parameter names, such as $ A, $ (starting from 0, representing the I parameter ...)
  17. * (4) provides trailing closure syntax (Trailing closure syntax)
  18. */
  19. //Use the Sort method in the swift standard library to simplify closures in a step-by-step manner
  20. //Sort function requires two parameters
  21. //Parameter one: array
  22. //Parameter two: A closure: With two parameters, these two parameter types are the same as the element types in the array, the return value is bool
  23. var names = ["Swift", "Arial", "Soga", "Donary"]
  24. //First way: Using Functions
  25. Func Backwards (firststring:string, secondstring:string), Bool {
  26. return firststring > Secondstring //ascending sort
  27. }
  28. //The second argument here, a function is passed
  29. //reversed is equal to ["Swift", "Soga", "Donary", "Arial"]
  30. var reversed = sort (nams, backwards)
  31. //Second way: Use closure mode
  32. //Complete closure The notation is a parameter list and a return value within the curly braces, indicating the beginning of the closure with the keyword in
  33. //(firststring:string, secondstring:string) closure parameter list
  34. //-bool indicates that the closure return value type is bool
  35. the//in keyword indicates the beginning of the closure body
  36. Reversed = sort (names, {(firststring:string, secondstring:string), Bool in
  37. return firststring > Secondstring
  38. })
  39. //This can be further simplified because the closure code is shorter and can be written on one line
  40. Reversed = sort (names, {(firststring:string, secondstring:string), Bool in return firststring > SecondS Tring})
  41. Here's a further simplification: automatically infer types based on environment context
  42. The argument list does not indicate a type, nor does it indicate a return value type, because Swift can be extrapolated from context
  43. The type of firststring and secondstring will be the type of the names array element, and the return value type will be based on the return statement result
  44. Reversed = sort (names, {firststring, secondstring in return firststring > secondstring})
  45. Further simplification: implicit return (single-line statement closure)
  46. Because the closure body has only one line of code, you can omit return
  47. Reversed = sort (names, {firststring, secondstring in Firststring > secondstring})
  48. Further simplification: Using simplified parameter names ($i, i=0,1,2 ... starting from 0)
  49. Swift infers that a closure requires two parameters, the same type as the names array element
  50. Reversed = sort (names, {$0 > $1})
  51. The simplest way to do this: using Operators
  52. Reversed = sort (names, >)
  53. /*
  54. * Trailing closures (Trailing Closures)
  55. * If the function requires a closure parameter as a parameter, and this parameter is the last parameter, and the closure expression is very long,
  56. * It is useful to use trailing closures. Trailing closures can be placed outside the function argument list, which is outside the brackets. If the function has only one argument,
  57. * Then you can omit the brackets () and follow the closures directly.
  58. */
  59. The array method map () requires a closure as a parameter
  60. Let strings = numbers. map { //Map function after () can be omitted
  61. (var number), String in
  62. var output = ""
  63. While number > 0 {
  64. Output = String (number% 10) + output
  65. Number/= 10
  66. }
  67. return Output
  68. }
  69. /* Capture Value
  70. * Closures can be captured to defined constants and variables according to the environment context. Closures can reference and modify these captured constants and variables,
  71. * Even if defined as a constant in the original scope or the variable no longer exists (very good).
  72. * The simplest form of closure in Swift is a nested function.
  73. */
  74. Func increment (#amount: int), ((), int) {
  75. var total = 0
  76. Func Incrementamount (), Int {
  77. Total + = Amount //Total is a variable in the body of an external function, which can be captured
  78. return Total
  79. }
  80. return incrementamount //Returns a nested function (closure)
  81. }
  82. Closures are reference types, so incrementbyten declarations as constants can also modify total
  83. Let Incrementbyten = Increment (amount: 10)
  84. Incrementbyten () //Return 10,incrementbyten is a closed package
  85. Here is no change to the increment reference, so the previous value will be saved
  86. Incrementbyten () //Return
  87. Incrementbyten () //Return
  88. Let Incrementbyone = Increment (amount: 1)
  89. Incrementbyone () //return 1
  90. Incrementbyone () //return 2
  91. Incrementbyten () //Return
  92. Incrementbyone () //Return 3

Swift Learning 14: Closures (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.