Swift Closure (closure)

Source: Internet
Author: User
Tags closure

The closure in Swift, the block in Objective-c, is actually a thing

Declaration of 1.Closure variables

(1) Closure is an anonymous function, we can define a closure variable, and the type of the closure variable is the "function type" we described above.

Defining a closure variable is actually a variable that defines a particular function type, in the following way.

Because the closure variable does not have an initial value assigned to it, we declare it as a variable of an optional type. When in use, use! Force to open.

    varmyCloure0:((Int, Int) -> Int)?

(2) We also use another common way of declaring closure variables. That is, using the keyword Typealias to define a specific function type,

We can take this type to declare a closure variable, as shown below

    //定义闭包类型 (就是一个函数类型)

      typealias MyClosureType = (Int, Int) -> Int       var myCloure:MyClosureType?

2. Assigning values to closure variables

Assigning a value to a closure variable is actually a variable that assigns a function body to a function type, and the definition of the function is not very different.

But the function body that assigns a value to a closure variable contains a list of parameters, and the argument list and the real function body are separated by the keyword in.

The closure optional variable is called in the same way as the normal function, the only difference is that the function needs to be opened to be used. The assignment and invocation are as follows.

  

int int int  inch       return NUM1 + num2;        } Myclosure! (ten)

Swift Closure (closure)

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.