Swift-Closure Understanding

Source: Internet
Author: User

/*Closures (Closures) * closures are self-contained functional code blocks that can be used in code or used as parameters to pass values.  * Closures in Swift are similar to the lambdas in C, OC, and other programming languages such as Python (blocks). * Closures can capture and store references to any constants and variables defined in the context. This is known as the self-enclosing of variables and variables, and is therefore named "Closures" ("Closures").  Swift also handles memory management for all captured references.  * * Global functions and nested functions are actually special closures.  * Closures are in the form of: * (1) Global functions are closures, have names but cannot capture any values.  * (2) Nested functions are closures and have names that can also capture values within the enclosing function.  * (3) The closure expressions are anonymous closures, which use lightweight syntax to capture values based on the context environment. * * There are a lot of optimizations for closures in Swift: * (1) by context inference parameter and return value type * (2) implicitly returned from a single-line expression closure (that is, the closed package has only one line of code, can omit return) * (3) can use simplified parameter names such as $ A, $ (0, table  Example I parameters ...) * (4) provides trailing closure syntax (Trailing closure syntax)*/      //use the Sort method in the swift standard library to simplify closures in a step-by-step manner//The sort function requires two parameters//parameter one: array//parameter two: A closure: With two parameters, these two parameter types are the same as the element type in the array, the return value is boolvar names = ["Swift","Arial","Soga","donary"]      //The first way: Using FunctionsFunc Backwards (firststring:string, secondstring:string)Bool {returnfirststring > Secondstring//Sort Ascending }   //Here's the second argument, a function is passed//reversed is equal to ["Swift", "Soga", "Donary", "Arial"]var reversed =sort (nams, backwards)//The second way: using closures//The complete closure is written in curly braces with a parameter list and a return value, using the keyword in to indicate the beginning of the closure body//(firststring:string, secondstring:string) closure parameter list//- BOOL indicates that the closure return value type is bool//The In keyword indicates the beginning of the closure bodyReversed = sort (names, {(firststring:string, secondstring:string), Boolinch      returnFirststring >secondstring}) //This can be further simplified because the closure code is shorter and can be written on one lineReversed = sort (names, {(firststring:string, secondstring:string), Boolinch returnFirststring >secondstring}) //here's a further simplification: automatically infer types based on environment context//The argument list does not indicate a type, nor does it indicate the return value type, because Swift can infer from the context//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 resultReversed = sort (names, {firststring, secondstringinch returnFirststring >secondstring}) //further simplification: implicit return (single-line statement closure)//because the closure body has only one line of code, you can omit returnReversed = sort (names, {firststring, secondstringinchFirststring >secondstring}) //further simplification: using simplified parameter names ($i, i=0,1,2 ... starting from 0)//Swift infers that a closure requires two parameters, the same type as the names array elementReversed = sort (names, {$0> $1 })      //the simplest way to do this: using OperatorsReversed = sort (names, >)                  /** Trailing closure (Trailing Closures) * If the function requires a closure parameter as a parameter, and this parameter is the last parameter, and this closure expression is very long, * 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 parameter, * then you can omit the parentheses () and follow the closure directly. */   //the Array method map () requires a closure as a parameterLet strings = Numbers.map {//the () after the map function can be omitted(var number), Stringinchvar output=""     whileNumber >0{Output= String (number%Ten) +Output Number/=Ten    }    returnOutput}/*Capture Value * Closures can be captured to defined constants and variables based on the environment context.  Closures can reference and modify these captured constants and variables, * even if defined as constants in the original scope or the variable no longer exists (very good).  * The simplest form of closure in Swift is a nested function. */func Increment (#amount: Int)((),Int) {var total=0func incrementamount ()-Int { Total+ = Amount//Total is a variable in the body of an external function, which can be captured    returnTotal }returnIncrementamount//The return is a nested function (closure)}           //closures are reference types, so incrementbyten declarations as constants can also modify totalLet Incrementbyten = Increment (amount:Ten) Incrementbyten ()//return 10,incrementbyten is a closed package//here is no change to the increment reference, so the previous value will be savedIncrementbyten ()//returnIncrementbyten ()//returnLet incrementbyone= Increment (Amount:1) Incrementbyone ()//return 1Incrementbyone ()//return 2Incrementbyten ()//returnIncrementbyone ()//return 3

Swift-Closure Understanding

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.