swift-06-Closure Package

Source: Internet
Author: User
Tags instance method

After reading not remember, had to continue to copy the text.


If the default value of a stored-type property requires special customization or preparation, you can use closures or global functions to provide custom default values for their properties. Whenever a new type instance of a property is created, the corresponding closure or function is called, and their return value is assigned to the property as the default value.

This type of closure or function typically creates a temporary variable that is the same as the property type, modifies its value to meet the expected initial state, and finally returns the value of the temporary variable as the default value for the property.

The formula is as follows:

Class SomeClass {    let Someproperty:sometype = {    //Create a default value for Someproperty in this closure//somevalue must and SomeType     type Same as    return somevalue    } ()}    

Note that the closing curly braces are followed by a pair of empty parentheses. This is used to tell Swift to execute this closure immediately. If this pair of parentheses is omitted, it is equivalent to assigning the closure itself as a value to the property instead of assigning the return value of the closure to the property.


If you use closures to initialize the value of a property, keep in mind that other parts of the sample are not initialized when the closure is executed. This means that it is not possible to ask other attributes in a closure, even if the property has a default value. Similarly, you cannot use the implicit Self property, or call another instance method.


swift-06-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.