The application of Swift's "closure package"

Source: Internet
Author: User
Tags closure

Believe that the swift, we should know that Swift abandoned the block in OC, but the application of the block is more flexible, the role is very powerful. Swift is certainly not lack of such a design pattern, so the introduction of closures, its function and function and OC block has the same kind of good, but in the wording, the gap is larger. This paper, mainly to explore the use of "closure" method.

A: Introduction to closures

1, the closure is also a function, what is the function? A function is a block of code. There's nothing to tangle with.
2, the use of closures, closures are mainly used in two ways, 1), closures in the application of the method. 2), closure in the properties of the application.

Two: The structure analysis of the closure package
  mathFunction:(text:String) -> Void

Mathfunction is the name of the closure (the name must be followed by a colon)
() inside the parentheses is the parameter
Text is the name of the parameter
String is a parameter type
, which indicates the return value type.
Note: If you want to take more than one parameter, the format is separated by commas (parameter: parameter type, parameter: parameter type).

Three: The application of closure in the method

Mode 1:
Inserting closures directly into a method

  /**闭包在方法中应用*/  func dataBack(str:String , mathFunction:(text:String) -> Void){ print("\(str)"); mathFunction(text: "这是闭包在方法中的应用"); }

This definition, with two parameters, one is the sting type, one is the closure, but the closure is more special, you can understand as parameters, you can have other understanding.

    mathFunction(text: "这是闭包在方法中的应用");

This code is called a closure, in this code, the method is called the closure, that is, when the method is called, the closure will be automatically called. If you want to call a closure somewhere else, it's time to use the property, not here, in mode two, I'll talk about it.

Method 2: Use Typealias to define closures and place them in methods and properties.

It acts as an alias, first defining a closure that is aliased to newfuncy.
Typealias newfuncy = (text:nsstring), Void;

Defines a myfuncy property whose type is newfuncy, and its effect is described below
var myfuncy:newfuncy?;

/**闭包在方法中第二种应用*/func secondDataBack(str:String , mathFunction:newFuncy){ print("\(str)"); self.myFuncy = mathFunction;}

This is a closure defined using the Typealias, in mode one, I'm calling the closure directly in the method, and here, what I'm going to say is, if you want to call a closure somewhere else, then, in the method, you'll assign the closure of the method to your own defined property closure, where you want to call the closure. , you can call this property. Believe it, everyone can understand it! If you do not understand, you can ask questions at any time.

Four: The use of attribute closures

If the above way, we feel more cumbersome, imagine block like, in the properties of simple and flexible use, here, I tell you, is possible.

First, define a closure property (you can also define it in Typealias way, of course)

//闭包的属性的用法var my:((text : NSString) -> Void)?;

We all know that when a block is defined as a property, we can use his set method directly, so that when the block is called, the code inside its set method executes, but the closed package can be used with the Set method? In Swift, the set method is more laborious to write, and the defined property cannot be called directly by the set method.

The author in the process of inquiry, is not successful to write its set method, if there is written out, I hope you can add in the comments, will be grateful.

Take a look at the writing I've explored myself!

//利用闭包属性传递消息,注意,此代码不能写在与属性闭包定义的同一个类里,   会崩溃,具体崩溃原因,正在思考。    viewC!.my = { (text) -> Void in        self.str = "sss"; print(text); }

This is the author's own exploration of a writing, so that when the closure is called, in the code will be executed. Inside the attention, I believe everyone also saw, interested can go to try, the author is currently guessing that the cause of the crash and the "View Builder". If there is a great God, can give a detailed explanation, I kneel thank ah.

The last point, but also a lot of beginners often easy to forget, that is in the attribute closure call, to add a judgment, add what judgment? -----> Determine if a closure exists. Why add judgment? ----> code is more secure in order to make logic more rigorous.

  if((self.my) != nil){      my!(text:"这是闭包在属性中的应用"); }

The method of judging, similar to the above code.

Five: A probe into the increase of reference count in closures like block

Define two attributes first, in fact two can be said as one.

var str:NSString?;var _str:NSString{    set{        str = newValue;    }    get{        return str!; }}

These two properties are then assigned values in the property closure, and in the method closure.

viewC!.my = { (text) -> Void in        self.str = "sss"; self._str = "ssss" }viewC?.dataBack("传给带闭包的方法的参数", mathFunction: { (text) -> Void in self.str = text; self._str = "ssss" });

Through the discovery, the author of the two types of closure, in its internal use of global variables, there will be no yellow warning, that is, the variable is not a reference count +1. Speaking of which, I suddenly think of a problem, Swift is also using arc to manage memory? Have the time to check the information, this is because the author when writing a simple book, suddenly think of, so I look after the author, in other articles write these.

If you have different understandings and opinions from the developers you are doing, you are welcome to discuss with me. Technology Group 512847147

The application of Swift's "closure package"

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.