Swift global variables, local variables and type attributes, swift global variables

Source: Internet
Author: User

Swift global variables, local variables and type attributes, swift global variables

Global and local variables

The pattern described by the calculation property and property monitor can also be used for global variables and local variables. global variables are variables defined outside functions, methods, closures, or any type, local variables are defined within functions, methods, or closures.

 

The global or local variables mentioned in the previous section are stored variables. Similar to the storage attributes, they provide specific types of storage space and allow reading and writing.

 

In addition, computing variables can be defined globally or locally and the monitor can be defined for storage variables. Computing variables return a calculated value, not a stored value, just like the computing attribute, the Declaration format is the same.

 

Note:

 

Global constants or variables are computed with delay. They are similar to delayed storage properties. The difference is that global constants or variables do not need to be marked with the @ lazy feature.

 

Constants or variables in the local range do not delay calculation.

 

Type property

The attributes of an instance belong to a specific type. Each time a type is instantiated, it has its own set of attribute values. The attributes of an instance are independent of each other.

 

You can also define attributes for the type. No matter how many instances the type has, these attributes are unique. This type of attribute is a type attribute.

 

Type attributes are used to define the data shared by all instances of a specific type. For example, a constant that can be used by all instances (just like a static constant in C ), or a variable that can be accessed by all instances (just like static variables in C ).

 

For value types (struct and enumeration), you can define storage and computing type attributes. For classes, you can only define computing type attributes.

 

The storage type attribute of the value type can be a variable or constant. The computing type attribute is defined as a variable attribute like the computing property of the instance.

 

Note:

 

Different from the storage properties of an instance, you must specify the default value for the storage type attribute, because the type itself cannot be used to assign values to the type attribute during initialization.

 

Type attribute syntax

In C or Objective-C, static constants and static variables are defined by adding the global keyword to a specific type. In Swift programming language, a type attribute is written in curly brackets on the outermost layer of a type as part of a type definition, so its scope of action is within the range supported by the type.

 

Use the keyword static to define the type attribute of the value type, and the keyword class to define the type attribute for the class. The following example demonstrates the syntax of the storage and computing type attributes:

 

Struct SomeStructure {static var storedTypeProperty = "Some value. "static var computedTypeProperty: Int {// here an Int value is returned} enum SomeEnumeration {static var storedTypeProperty =" Some value. "static var computedTypeProperty: Int {// here an Int value is returned} class SomeClass {class var computedTypeProperty: Int {// here an Int value is returned }}


Note:

 

The computing type attribute in this example is read-only, but can also define readable and writable computing type attributes, similar to the syntax of instance computing properties.

 

Get and set the value of the type attribute

Like instance attributes, access to type attributes is also carried out through the dot operator. However, type attributes are obtained and set through the type itself, rather than through the instance. For example:

 

Println (SomeClass. computedTypeProperty) // output "42" println (SomeStructure. storedTypeProperty) // outputs "Somevalue. "SomeStructure. storedTypeProperty = "Another value. "println (SomeStructure. storedTypeProperty) // output "Anothervalue."


The following example defines a struct that uses two storage type attributes to represent the sound level value of multiple channels. Each channel has an integer between 0 and 10 to indicate the sound level value.

 

The following figure shows how two sound channels are combined to represent the sound level of a stereo. When the channel level is 0, no lamp is on; when the channel level is 10, all lights are on. In this figure, the level of the left audio channel is 9, and the level of the right audio channel is 7.

 

 

 

The channel model described above uses the AudioChannel struct to represent it:

 

Struct AudioChannel {static let thresholdLevel = 10 static var maxInputLevelForAllChannels = 0 var currentLevel: Int = 0 {didSet {if currentLevel> AudioChannel. thresholdLevel {// set the new electric flat value to the threshold value currentLevel = AudioChannel. thresholdLevel} if currentLevel> AudioChannel. maxInputLevelForAllChannels {// store the current level value as the new maximum input level AudioChannel. maxInputLevelForAllChannels = currentLevel }}}}


The structure AudioChannel defines two storage type attributes to implement the above functions. The first is thresholdLevel, which indicates the maximum threshold of the sound level. It is a constant with a value of 10 and is visible to all instances. If the sound level is higher than 10, the maximum value is 10 (see the description below ).

 

The second type attribute is the storage type attribute maxInputLevelForAllChannels, which indicates the maximum value of the level value of all AudioChannel instances. The initial value is 0.

 

AudioChannel also defines an Instance Storage attribute named currentLevel, indicating the current level value of the current channel. The value ranges from 0 to 10.

 

The property currentLevel contains the didSet property monitor to check the attribute values after each new setting. There are two checks:

 

If the new value of currentLevel is greater than the allowed threshold value thresholdLevel, property monitor limits the value of currentLevel to the threshold value thresholdLevel.

If the corrected currentLevel value is greater than any previous AudioChannel value, property monitor stores the new value in the static attribute maxInputLevelForAllChannels.

Note:

 

During the first check, the didSet property monitor sets currentLevel to a different value, but does not call the property monitor again.

You can use the structure AudioChannel to create two channels leftChannel and rightChannel representing the stereo system:

 

var leftChannel = AudioChannel()var rightChannel = AudioChannel()


If you set the level of the left channel to 7, the type attribute maxInputLevelForAllChannels is also updated to 7:

 

LeftChannel. currentLevel = 7 println (leftChannel. currentLevel) // output "7" println (AudioChannel. maxInputLevelForAllChannels) // output "7". If you try to set the right channel level to 11, the currentLevel of the right channel is corrected to the maximum value of 10, and the value of maxInputLevelForAllChannels is also updated to 10: rightChannel. currentLevel = 11 println (rightChannel. currentLevel) // output "10" println (AudioChannel. maxInputLevelForAllChannels) // output "10"



Storage of local variables, global variables, and external variables

Variable category:
Global variables and local variables can be divided according to the scope.
According to the life cycle, there can be divided into static storage and dynamic storage, specifically divided into automatic (auto), static (static), register (register), external (extern ).
Static storage is used to allocate a fixed storage space during the running of the program. Dynamic Storage is used to dynamically allocate storage space as needed during the running of the program.

Each variable has two attributes: scope and storage class. These attributes are used together to describe a variable. The relationships between these variables and storage locations are as follows:
External variables (global variables), static external variables, and static local variables are stored in the static storage area.
Automatic local variables (local variables are automatic local variables by default) and function parameters are stored in the dynamic storage area. Both static and dynamic storage areas belong to the user area in the memory.
However, register variables are stored in CPU registers rather than memory.

First, describe several attributes related to the scope:
Local variables: the variables defined in a function are internal variables, which are valid only within the scope of the function, that is, they can be used only in the function, these variables cannot be used outside of this function. Such variables are called "local variables ".
Global variables: variables defined outside the function can be shared by other functions in the source file. The valid range is from the position of the defined variable to the end of the source file, this type of variable is called "global variable ".

The following describes the attributes related to the storage type:
Atuo: When declaring local variables, if static is not specified, auto is used by default. These variables are dynamically allocated to the storage space and the data is stored in the dynamic storage area.
Static: When declaring a local variable, use the keyword static to specify the local variable as a "static local variable", so that the original value will not disappear after the function call ends, that is, the occupied storage units are not released. The existing value of this variable is the value at the end of the last function call when the callback function is called.
Register: When declaring dynamic local variables or function parameters, you can declare the variables as register, so that the compilation system allocates a register for the variables instead of the memory space, this method can improve the performance of programs that frequently call certain local variables. (Register operation speed is much higher than memory)
Extern: used to extend the scope of a global variable. For example, if the function wants to reference an external variable but the external variable is defined after the function, the function needs to use extern to declare the variable, in this way, the global variables defined after the function can be used. In addition, extern can declare external variables in Multi-file programs.

Variables are divided from different dimensions to form a variety of complex relationships, so you need to focus on learning programming.

Java local variables and global variables

First look at this example
--------------------------------------------------------------
Public class Variable {
// Member variable
String name = "member variable ";

Public static void main (String [] args ){
// Create a Class Object
Variable variable = new Variable ();
// Call the local method of the object
Variable. local ();
}

Void local (){
// Local variable
String name = "local variable ";
// Print the variable name in the method body
System. out. println (name );
// Use this to point to the object itself. this. name, as an object (Variable Class Object)
System. out. println ("Print:" + this. name );
}

}
---------------------------------------------------------
Let's look at this example.
----------------------------------------------------
Public class Variable {
// Member variable
String name = "member variable ";

Public static void main (String [] args ){
// Create a Class Object
Variable variable = new Variable ();
// Call the local method of the object
Variable. local ();
Variable. local2 ("unknown ");
}

Void local (){
// Local variable
String name = "local variable ";
// Print the variable name in the method body
System. out. println (name );
// Use this to point to the object itself. this. name, as an object (Variable Class Object)
System. out. println ("Print:" + this. name );
}

Void local2 (String name ){
// Value of the member variable name, which is equal to the passed namn Value
// That is, the parameter passed by the method. The parameter name can be changed at will.
// This also points to the current object, such as the variable object instantiated in the main method.
// Here, the value of the name variable in the current object is changed, but the value of the local variable name is not affected.
This. name = name;
// Name or local variable printed here
// That is, the parameter passed in by the method
System. out. println ("I printed the value of a local variable" + name );
}
}
--------------------- ...... Remaining full text>

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.