Initialization and reverse initialization in Swift programming fully explained _swift

Source: Internet
Author: User
Tags constant numeric value

Class
classes, structs, and enumerations are prepared to initialize class instances after Swift declaration. The initial value is initialized to store the property, and the value of the new instance is further initialized. The key word for creating the initialization function is through the init () method. Swift initialization differs from OBJECTIVE-C, and it does not return any values. The effect is to check the initialization of the newly created instance before it is processed. Swift also provides memory management operations performed during the "anti-initialization" process when an instance is released.

The role of the stored property initializer
An instance of a class and struct is initialized before the stored property processes the instance. Storage properties Use initial allocation and initialization values, eliminating the need to invoke property observers. Initialize for storage properties:

Create an initial value

To specify default property values in the attribute definition

For a specific data type, the initialization instance init () method is used and the init () function does not pass parameters.

Grammar

Copy Code code as follows:

Init ()
{
New Instance initialization goes here
}



Example


Copy Code code as follows:

struct Rectangle {
var length:double
var breadth:double
Init () {
Length = 6
Breadth = 12
}
}
var area = Rectangle ()
println ("area of rectangle is \ (area.length*area.breadth)")



When we use playground to run the above program, we get the following results.

Area of rectangle is 72.0

Here the structure ' rectangle ' is initialized with a data type with a member's width and height of "double". The init () method is used for the length of the newly created member and the numeric value of the initialization double type. Computes the area of the rectangle and returns it by calling the rectangular function.

Setting property values By default
The Swift language provides the init () function to initialize the stored property values. In addition, the user must specify the default attribute value to initialize the member of the declaring class or struct. When the value of a property is the same in the entire program, we can declare it separately in the Declarations section, rather than initializing it in Init (). By default, a user can inherit a property value when it is set to be defined as a class or struct.

Copy Code code as follows:

struct Rectangle {
var length = 6
var breadth = 12
}
var area = Rectangle ()
println ("area of rectangle is \ (area.length*area.breadth)")



When we use playground to run the above program, we get the following results.

Area of rectangle is 72.0

Here, instead of declaring long and wide in init (), the value is initialized when the declaration itself.

Parameter initialization
The Swfit language user provides initialization with initialization parameters and uses the definition as part of Init ().

Copy Code code as follows:



struct Rectangle {


var length:double


var breadth:double


var area:double





Init (fromlength length:double, Frombreadth breadth:double) {


Self.length = length


Self.breadth = Breadth


Area = length * breadth


}





Init (Fromleng leng:double, Frombread bread:double) {


Self.length = Leng


Self.breadth = Bread


Area = Leng * Bread


}


}

Let AR = Rectangle (fromlength:6, Frombreadth:12)
println ("area is: \ (Ar.area)")

Let are = Rectangle (fromleng:36, Frombread:12)
println ("area is: \ (Are.area)")




When we use playground to run the above program, we get the following results.

Area is:72.0 Area
is:432.0

Local and external parameters
The initialization parameter has a similar function and method parameter local and global parameter names. A local parameter declaration is used for initializing the body, and an external parameter declaration access is used to invoke initialization. Swift function initialization and methods are different, and they do not recognize which initialization is used for the function call.

To overcome this problem, Swift introduces each parameter with an automatic external name of init (). This automatic external name is equivalent to the local name of each initialization parameter written before.

Copy Code code as follows:



struct Days {


Let Sunday, Monday, Tuesday:int


Init (Sunday:int, Monday:int, Tuesday:int) {


Self.sunday = Sunday


Self.monday = Monday


Self.tuesday = Tuesday


}





Init (daysofaweek:int) {


Sunday = Daysofaweek


Monday = Daysofaweek


Tuesday = Daysofaweek


}


}

Let week = Days (Sunday:1, Monday:2, Tuesday:3)
println ("Days of a Week are: \ (week.sunday)")
println ("Days of a Week are: \ (week.monday)")
println ("Days of a Week are: \ (week.tuesday)")

Let weekdays = Days (Daysofaweek:4)
println ("Days of a Week are: \ (weekdays.sunday)")
println ("Days of a Week are: \ (weekdays.monday)")
println ("Days of a Week are: \ (weekdays.tuesday)")




When we use playground to run the above program, we get the following results.

Days of a Week is:1 days of
a Week is:2 days of
a Week is:3 days of a Week is:4 days of
a Week is:4
   days of a Week is:4

Without external name parameters
when an external name does not require an initialization underscore "_", this is used to override the default behavior.

Copy Code code as follows:

struct Rectangle {
var length:double

Init (Frombreadth breadth:double) {
Length = breadth * 10
}

Init (Frombre bre:double) {
Length = bre * 30
}

Init (_ area:double) {
Length = Area
}
}

Let Rectarea = Rectangle (180.0)
println ("area is: \ (rectarea.length)")

Let Rearea = Rectangle (370.0)
println ("area is: \ (rearea.length)")

Let Recarea = Rectangle (110.0)
println ("area is: \ (recarea.length)")




When we use playground to run the above program, we get the following results.

Area is:180.0 Area
is:370.0 area
is:110.0

Optional attribute type
when some instances store properties that do not return any value this property uses the "optional" type, indicating "no value" to return a specific type of declaration. When a stored property is declared as "optional", it automatically initializes the value as ' nil ' during its initialization.

Copy Code code as follows:

struct Rectangle {
var length:double?

Init (Frombreadth breadth:double) {
Length = breadth * 10
}

Init (Frombre bre:double) {
Length = bre * 30
}

Init (_ area:double) {
Length = Area
}
}

Let Rectarea = Rectangle (180.0)
println ("area is: \ (rectarea.length)")

Let Rearea = Rectangle (370.0)
println ("area is: \ (rearea.length)")

Let Recarea = Rectangle (110.0)
println ("area is: \ (recarea.length)")




When we use playground to run the above program, we get the following results.

Area is:optional (180.0) area
is:optional (370.0) area
is:optional (110.0)

Modifying a constant property when initializing
initialization also allows the user to modify the value of a constant property. During initialization, the class property allows instances of its classes to be modified by superclass rather than by subclasses. Consider the example of the previous program "Length", which is declared as the main class "variable". The following program variable ' length ' is modified to ' constant ' variable.

Copy Code code as follows:

struct Rectangle {
Let length:double?

Init (Frombreadth breadth:double) {
Length = breadth * 10
}

Init (Frombre bre:double) {
Length = bre * 30
}

Init (_ area:double) {
Length = Area
}
}

Let Rectarea = Rectangle (180.0)
println ("area is: \ (rectarea.length)")

Let Rearea = Rectangle (370.0)
println ("area is: \ (rearea.length)")

Let Recarea = Rectangle (110.0)
println ("area is: \ (recarea.length)")




When we use playground to run the above program, we get the following results.

Area is:optional (180.0) area
is:optional (370.0) area
is:optional (110.0)

Default initializer
default Initializes a new instance default value for all declared properties that are provided to the base class or struct.

Copy Code code as follows:

Class Defaultexample {
var studname:string?
var Stmark = 98
var pass = True
}
var result = Defaultexample ()

println ("result is: \ (result.studname)")
println ("result is: \ (Result.stmark)")
println ("result is: \ (result.pass)")




When we use playground to run the above program, we get the following results.

Result Is:nil result
is:98 result
is:true

The name of the class is "defaultexample" defined in the above program. Three member functions are initialized by default to "Studname?" "True" for the Boolean value "store value is ' nil '," Stmark "is 98 and" pass ". Similarly, the values of the members in the class are initialized to the default values before they can be processed by the class member type.

By member initializer structure type
when user-defined initialization is not provided, the swift struct type will automatically receive "member initialization". Its primary function is to initialize the default member that initializes the new struct instance, and then to initialize the new instance property by name to the member.

Copy Code code as follows:

struct Rectangle {
var length = 100.0, breadth = 200.0
}
Let-area = Rectangle (length:24.0, breadth:32.0)

println ("Area of rectangle is: \ (area.length)")
println ("Area of rectangle is: \ (area.breadth)")




When we use playground to run the above program, we get the following results.

Area of rectangle is:24.0 area of
rectangle is:32.0

Structs are initialized by default to "Length" to "100.0" and "breadth" to "200.0", while initialization is their member function. However, variable values for length and width are overwritten with 24.0 and 32.0 in the process.

Initializing a delegate value type
the initial delegate definition invokes the initialization of other initialization functions. Its primary function is to act as a reusability to avoid duplication of multiple initialization code.

Copy Code code as follows:



struct Stmark {


var mark1 = 0.0, Mark2 = 0.0


}


struct STDB {


var m1 = 0.0, m2 = 0.0


}

struct Block {
var average = Stdb ()
var result = Stmark ()

Init () {}

Init (Average:stdb, Result:stmark) {
Self.average = Average
Self.result = result
}

Init (Avg:stdb, Result:stmark) {
Let tot = avg.m1-(RESULT.MARK1/2)
Let tot1 = avg.m2-(RESULT.MARK2/2)
Self.init (Average:stdb (M1:tot, m2:tot1), Result:result)
}
}

Let Set1 = Block ()
println ("Student result is: \ (set1.average.m1, set1.average.m2) \ (SET1.RESULT.MARK1, SET1.RESULT.MARK2)")

Let Set2 = Block (Average:stdb (m1:2.0, m2:2.0),
Result:stmark (mark1:5.0, mark2:5.0))
println ("Student result is: \ (set2.average.m1, set2.average.m2) \ (SET2.RESULT.MARK1, SET2.RESULT.MARK2)")

Let Set3 = Block (Avg:stdb (m1:4.0, m2:4.0),
Result:stmark (mark1:3.0, mark2:3.0))
println ("Student result is: \ (set3.average.m1, set3.average.m2) \ (SET3.RESULT.MARK1, SET3.RESULT.MARK2)")




When we use playground to run the above program, we get the following results.

(0.0,0.0) (0.0,0.0)
(2.0,2.0) 5.0,5.0)
(2.5,2.5) (3.0,3.0)

Initializing function delegation rules

class Inherits and initializes the
The class type has two initialization functions to check whether the storage property is defined to receive the initial value, that is, to specify initialization and convenient initialization functions.

Specifying initialization and ease of initialization

PROGRAM Specifies initialization

Copy Code code as follows:

Class MainClass {
var no1:int//Local Storage
Init (no1:int) {
Self.no1 = no1//initialization
}
}
Class Subclass:mainclass {
var no2:int//New Subclass Storage
Init (No1:int, No2:int) {
SELF.NO2 = NO2//initialization
Super.init (NO1:NO1)//Redirect to Superclass
}
}

Let res = MainClass (no1:10)
Let print = Subclass (No1:10, no2:20)

println ("res is: \ (res.no1)")
println ("res is: \ (print.no1)")
println ("res is: \ (PRINT.NO2)")




When we use playground to run the above program, we get the following results.

Res is:10
Res is:10
Res is:20

Easy initialization of programs

Copy Code code as follows:



Class MainClass {


var no1:int//Local Storage


Init (no1:int) {


Self.no1 = no1//initialization


}


}

Class Subclass:mainclass {
var no2:int
Init (No1:int, No2:int) {
Self.no2 = NO2
Super.init (NO1:NO1)
}
Requires only one parameter for convenient
Override convenience init (No1:int) {
Self.init (No1:no1, no2:0)
}
}
Let res = MainClass (no1:20)
Let print = Subclass (no1:30, no2:50)

println ("res is: \ (res.no1)")
println ("res is: \ (print.no1)")
println ("res is: \ (PRINT.NO2)")




When we use playground to run the above program, we get the following results.

Res is:20
Res is:30
Res is:50

Initializing inheritance and overrides
Swift does not allow its subclasses to inherit its superclass initialization function as a member type by default. Inheritance applies to superclass initialization only to some extent, this will be discussed in the automatic initialization program inheritance.

When a user needs to have an initializer defined in a superclass, subclass, the initialization function must be defined by the user as the custom implementation. When overridden, it must be declared using the "override" keyword in subclasses to superclass.

Copy Code code as follows:

Class Sides {
var corners = 4
var description:string {
Return "\ (corners) sides"
}
}
Let rectangle = Sides ()
println ("Rectangle: \ (rectangle.description)")

Class Pentagon:sides {
Override Init () {
Super.init ()
Corners = 5
}
}

Let bicycle = Pentagon ()
println ("Pentagon: \ (bicycle.description)")




When we use playground to run the above program, we get the following results.

Rectangle:4 sides
Pentagon:5 Sides

Specifying and convenient initialization in action

Copy Code code as follows:



Class Planet {


var name:string





Init (name:string) {


Self.name = Name


}





Convenience init () {


Self.init (name: [No planets])


}


}


Let Plname = Planet (name: "Mercury")


println ("Planet name is: \ (plname.name)")

Let Noplname = Planet ()
println ("No planets like that: \ (noplname.name)")

Class Planets:planet {
var count:int
Init (name:string, Count:int) {
Self.count = Count
Super.init (Name:name)
}

Override convenience init (name:string) {
Self.init (Name:name, count:1)
}
}




When we use playground to run the above program, we get the following results.

Planet name Is:mercury
no planets like that: [No planets]

Failable Initialization Device
the user must be notified when any initialization of a class, struct, or enumeration value fails. Variable initialization can sometimes become a failure because:

    • Invalid parameter value
    • The required external source is missing
    • Conditional blocking Initialization success

To capture the exception of thrown initialization methods, swift processing produces a flexible initialization called "failable initialization" notification, which is left to be neglected in the initialization structure, class or enumeration member. Keyword capture failable initial value set "Init?". In addition, failable and failable initialization functions cannot be defined using the same parameter type and name.

Copy Code code as follows:

struct Studrecord {
Let stname:string

Init? (stname:string) {
If Stname.isempty {return nil}
Self.stname = Stname
}
}

Let Stmark = Studrecord (stname: "Swing")
If let name = Stmark {
println ("Student name is specified")
}

Let Blankname = Studrecord (stname: "")
if Blankname = = Nil {
println ("Student name is left blank")
}




When we use playground to run the above program, we get the following results.

Student name is specified
Student name is left blank

Failable The initial value is set to an enumeration
The Swift language provides the flexibility to use the Failable initialization function to notify users to enumerate member values from initialization.

Copy Code code as follows:



Enum Functions {


Case A, B, C, D


Init? (funct:string) {


Switch Funct {


Case "one":


Self =. A


Case "two":


Self =. b


Case "three":


Self =. C


Case "Four":


Self =. D


Default


return Nil


}


}


}

Let result = Functions (funct: "Two")
If result!= Nil {
println ("with in Block two")
}

Let Badresult = Functions (funct: "Five")
if Badresult = = Nil {
println ("Block does not Exist")
}




When we use playground to run the above program, we get the following results.

With in block two blocks
does not Exist

Failable initializer class
when an enumeration and struct declaration failable initialization of a reminder fails, any situation in the implementation. However, failable Initializes a reminder in the class before storing the initial value of the property setting.

Copy Code code as follows:

Class Studrecord {
Let studname:string!
Init? (studname:string) {
Self.studname = Studname
If Studname.isempty {return nil}
}
}
If Let Stname = Studrecord (studname: "failable initializers") {
println ("Module is \ (stname.studname)")
}



When we use playground to run the above program, we get the following results.

Module is failable initializers

Overwrite a failable initializer
This initialization user also has failable initialization that provides subclasses to overwrite the superclass. Superclass failable initialization can also be overridden in subclasses that are not failable initialized.

When overriding a failable superclass initialization, the initializer of the Nonfailable subclass initialization subclass cannot be delegated to the superclass initializer.

A nonfailable initialization cannot be delegated to a failable initialization.

The program described below describes failable and failable initialization functions.

Copy Code code as follows:



Class Planet {


var name:string





Init (name:string) {


Self.name = Name


}





Convenience init () {


Self.init (name: [No planets])


}


}


Let Plname = Planet (name: "Mercury")


println ("Planet name is: \ (plname.name)")

Let Noplname = Planet ()
println ("No planets like that: \ (noplname.name)")

Class Planets:planet {
var count:int

Init (name:string, Count:int) {
Self.count = Count
Super.init (Name:name)
}

Override convenience init (name:string) {
Self.init (Name:name, count:1)
}
}




When we use playground to run the above program, we get the following results.

Planet name Is:mercury
no planets like that: [No planets] 

Init! Failable Initialization Device
Swift offers "init?" Defines an optional instance of failable initialization. To define a specific type of implicit unpack optional ' int! ' is specified.

Copy Code code as follows:

struct Studrecord {
Let stname:string

Init! (stname:string) {
If Stname.isempty {return nil}
Self.stname = Stname
}
}

Let Stmark = Studrecord (stname: "Swing")
If let name = Stmark {
println ("Student name is specified")
}

Let Blankname = Studrecord (stname: "")
if Blankname = = Nil {
println ("Student name is left blank")
}




When we use playground to run the above program, we get the following results.

Student name is specified
Student name is left blank

Required initialization
declare and initialize each subclass, and the "required" keyword needs to be defined before the Init () function.

Copy Code code as follows:

Class ClassA {
Required Init () {
var a = 10
println (a)
}
}

Class Classb:classa {
Required Init () {
var B = 30
println (b)
}
}
Let res = ClassA ()
Let print = CLASSB ()




When we use playground to run the above program, we get the following results.

Ten
10

Reverse initialization
before a class instance needs to be deallocated, "Deinitializer" is called to free up memory space. The keyword "Deinit" is used to free up storage space occupied by system resources. The inverse initialization applies only to the class type.

Reverse Initialize and free memory space
Swift frees up resources by automatically canceling the allocation of instances when they are no longer needed. Swift handles memory management of instances through automatic reference counting (ARC), such as automatic reference count descriptions. Typically, the instance is freed automatically without manual cleanup. However, when you are using your own resources, you may need to do some extra cleanup yourself. For example, if you create a custom class to open a file and write some data, you might want to close the file before the class instance is released.

Copy Code code as follows:

var counter = 0; For reference counting
Class BaseClass {
Init () {
counter++;
}
Deinit {
counter--;
}
}

var print:baseclass? = BaseClass ()
println (counter)
Print = Nil
println (counter)




When we use playground to run the above program, we get the following results.

1
0

When the print = Nil statement omits the value of the counter, it remains unchanged because it does not have a reverse initialization.

Copy Code code as follows:

var counter = 0; For reference counting

Class BaseClass {
Init () {
counter++;
}

Deinit {
counter--;
}
}

var print:baseclass? = BaseClass ()

println (counter)
println (counter)




When we use playground to run the above program, we get the following results.

1
1

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.