Closures in Swift (Closure) [Go]

Source: Internet
Author: User
Tags closure

Closures are very useful in swift. The popular explanation is that an int is stored with a string containing a string of characters, and the closure is a type that contains the 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 map method of the array ? 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.

the map function is prototyped as follows:

func map<U>(transform: (T ) u), [u]

We can see that the function uses generics. (T)-U is a generic closure, which means that type T will be logically processed in the closure and then return the u type. the last map function returns an array of type U.

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 Greetpeople to generate a welcome word for everyone:

func greetpeople (person: String), string

{

return "Hello, \ (person)!"

}

Let guestlist = ["Chris", "Jill", "Tim"]

Let fullgreetings = guestlist.map (greetpeople)

The greetpeople function is then passed as a parameter to the map function of the guestlist array , and a new array fullgreetings is returned . This 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 a question,println function is not no return value? So what does the map function return? In fact, every function that has no return value returns an empty tuple (tuple), so the return value of the above code is actually array< () >.

In the above example, 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 the global function of greetpeople, it only needs to be used once, so we don't need to define this function separately. We can directly use a closure expression to handle:

Let fullgreetings = guestlist.map ({(Person: String) String in return "Hello, \ (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. In the above code, you can see that the keyword in is preceded by the argument and return value of the closure expression, followed by the area of code where the closure expression actually handles the logic.

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.map ({person), String in return "Hello, \ (person)!" })

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

Let fullgreetings = guestlist.map ({person ' in ' Hello, \ (person)! " })

In fact, Swift also provides a shorthand for the parameter:$ A represents the first argument, the second parameter, and so on . So we can omit the parameter name:

Let fullgreetings = guestlist.map ({ "Hello, \ ($)!") })

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

Let fullgreetings = guestlist.map () { "Hello, \ ($)!" }

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

Let fullgreetings = guestlist.map{ "Hello, \ ($)!" }

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

Closures in Swift (Closure) [Go]

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.