13. Initialize Initialization

Source: Internet
Author: User

1. Overview

Creates an instance of a class, struct, and enumeration by defining the constructor initializers . Unlike Objective-c's initializers, initializers in Swift does not have a return value.

An instance of class types can also implement the destructor Deinitializerto clean up before the class is freed.

2. Initialization of the stored Properties (Setting Initial Values for stored properties)

The stored properties of classes and structs must have appropriate values when their instances are created.

You can initialize them in the constructor, or you can set default values for them at the time of definition.

Note: The property monitor will not be called when initializing the stored attribute, either by using the default value initialization or by invoking the constructor initialization.

2.1 Constructor initializers

A constructor is a init method with no parameters defined by a keyword that is used to create an instance of a type:

    init () {      //  perform some initializationhere    }

Such as:

    struct Fahrenheit {  // Fahrenheit temp    varDouble    init () {    32.0      }    }    var f = Fahrenheit ()    println(" the default temperature is \ (f.temperature) °fahrenheit")    // prints "The default temperature is 32.0°fahrenheit"  

2.2 Default Parameter value defaults property values

When a parameter always has an identical initialization value, it is better to use the default parameter value than to initialize it in the constructor. Of course their results are the same

    struct Fahrenheit {      var32.0    }

3. Custom initialization method Customizing initialization

The following example defines the two initializers of a struct Celsius for initializing different ranges of temperatures:

13. Initialize Initialization

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.