A brief analysis of closures (Closure) in Swift

Source: Internet
Author: User
Tags closure

Reprinted from: http://www.devtalking.com/articles/closure-expressions-in-swift/

Closures are very useful in swift. The popular explanation is that a Int type stores an integer, a String type that contains a string of characters, and a closure is a type that contains a function. With closures, you can handle a lot of things that you can't handle in some ancient language. This is because of the diversity of closures, such as you can assign a closure to a variable, you can also use closures as a function parameter, and you can even use closures as the return value of a function. Its strength is evident.

In many of Swift's documentation textbooks, the function is "first-class citizen", but I didn't quite understand the meaning of "A-class citizen" at the beginning, but when I understood the closure and its powerful function, I suddenly realized, enlightened and clairvoyant. The original closure of these features is "a citizen" characteristics Ah! See also Wikipedia first-class citizen.

Closures in Swift are similar to blocks in Objective-c. In fact, if you want to implement the block function in Objective-c in swift, you can use closures instead. The difference between blocks and closures is only different from the syntax, and the readability of the closures is relatively strong.

Is the function a closed packet?

Although you're not aware of it yet, we do have it in swift. The functions in Swift are closures, which are described in Apple's official documentation:

Closures are available in three different forms:

  1. A global function is a closed packet that has a name but does not capture any value.
  2. A nested function is a closure that has a name and can capture the value within its enclosing function domain.
  3. A closure expression is an anonymous closure that is written with lightweight syntax that captures variables or constant values in its context.

Today, we are going to discuss the third form, in particular how it compresses the cumbersome, less readable, business logic code into a highly readable, straightforward form.

Do you remember the method of array map ? Its argument is a closure that will handle each element in the array in a closure, and then return a new array, even a new array of different element types from the original array.

mapThe prototype of the function is as follows:


Map<U>u) [u]

We can see that the function uses generics. (T) -> Uis a generic closure, which means that the type will be T logically processed in the closure and then returned to the U type. mapThe last function returns an U array of type.

Use an example to illustrate. Today I have a birthday party, to greet a lot of people, and for everyone has prepared a welcome word. What are we going to do about it? First we put the greeted person in an array called guestList , and then use a function called a name greetPeople to generate a welcome word for everyone:

  
func greetpeople (person:string) string
{
return "Hello, \ (person)!"


let guestlist = [ let fullgreetings = Guestlist. Map (greetpeople)

The function is then greetPeople passed in as a guestList function of the array, map and a new array is returned fullGreetings , and the array contains everyone's welcome word.

If we want to show everyone the welcome word, we can even write this:


Fullgreetings. map (println)

At this point, there may be some questions, the println function is not the return value? So map what does the function return? In fact, every function that has no return value will return an empty tuple ( tuple ), so the return value of the above code is actually Array<()> .

In the example above, we are using a global function greetPeople as a closure.

A concise, closed-packet expression

In fact, Swift has provided us with a lot of simplified syntax that allows us to ensure that the code is highly readable and maintainable. We also use the above example to illustrate that, for greetPeople this global function, it is only necessary to use one time, so we do not need to define this function separately. We can directly use a closure expression to handle:


Let fullgreetings = guestlist. \ (person)! "})

The closure expression is actually the literal value of the function, which is generally called an anonymous function. Generally when we need to use a function to quickly implement a short processing logic and use it only once, we can omit the function name and use the simplified syntax. The above code can see that the keyword in is preceded by the argument and return value of the closure expression, followed by the in code area of the actual processing logic of the closure expression.

Below we will use Swift's more features to further simplify the closure expression.

We know that there are type inference features in Swift, so we can take out the parameter types:


Let fullgreetings = guestlist. \ (person)! "})

Like this single-closure expression in our example, the compiler can automatically judge based on the in previous return value type and return the return data type, so we can omit the return value and the return keyword:


Let fullgreetings = guestlist. \ (person)! "})

In fact, Swift also provides shorthand for parameters: representing the $0 first parameter, representing the second parameter, and so on $1 . So we can omit the parameter name:


Let fullgreetings = guestlist. \ ($0)! "})

When the last parameter of the function is a closure, the closure can be written out () , which is also a feature of Swift, so we can continue to simplify:


Let fullgreetings = guestlist. \ ($0)! "}

When a function has and has only one parameter, and the parameter is a closure, not only can the closure be written () out, but it can also be omitted () :


Let fullgreetings = guestlist. \ ($0)! "}

So far, the closure expression in the example has been simplified to a concise, highly readable closure expression based on Swift's characteristics, isn't it cool!

Reference Original: Closure Expressions in Swift

A brief analysis of closures (Closure) in Swift

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.