Swift language guide (I) -- constants and variables of language basics

Source: Internet
Author: User

Swift is a new programming language for developing iOS and OS X applications. However, Swift has many similarities with C or Objective-C.

Swift provides all the basic types in C and Objective-C, including the Int that represents the integer, the Double and Float that represents the floating point, the Bool that represents the Boolean value, and the String that represents the plain text data. Swift also provides powerful support for two basic Collection Types: Array and Dictionary. For details, see Collection Types.

Similar to C, Swift uses variables to store data and uses identifiers to reference variable values. Swift also expands the variable-value volume, that is, a constant, to make it much more powerful than a constant in C. When you do not need to change the value of data in Swift, using constants can make the code safer and simpler.

In addition to common types, Swift also introduces advanced types that do not exist in Objective-C, including tuple, which allows you to create or pass a set of values. A function can return multiple values as a whole (a combination of multiple values) to the caller.

Swift also introduces optional values (optional types) to process nonexistent values. Optional value:"ExistOne ValueX", Or"Does not existAny value ". The optional value is similar to that of Objective-C that assigns nil to the pointer, but can be used for any type in Swift, not for classes. The optional value is safer and more semantic than the nil pointer of Objective-C, and has been deeply used in Swift's most powerful functions.

The value is Swift.Type Security. Swift helps you clearly understand the data types that code can process. If the code wishes to get the String type, the type security feature will prevent you from mistakenly passing the Int type. In this way, problems can be detected and corrected as early as possible during the development process.

 

Constants and variables

Constants and variables associate names (such as maximumNumberOfLoginAttempts or welcomeMessage) with specific types of values (such as numbers 10 or strings "Hello.ConstantOnce assigned, the value cannot be changed.VariableYou can assign a value again later.

Declaration of constants and variables

Before using constants and variables, you must use the let keyword and var keyword respectively. The following example shows how constants and variables track User Logon times:

1 let maximumNumberOfLoginAttempts = 102 var currentLoginAttempt = 0

The code in the preceding example can be interpreted as: declare a constant named maximumNumberOfLoginAttempts, with a value of 10. Declare a variable currentLoginAttempt and initialize it to 0.

The maximum number of logon attempts allowed is assigned to a constant because the maximum number of logon attempts remains unchanged at runtime, and the current number of logon attempts is assigned to a variable, this is because the number of failed login attempts is cumulative.

You can assign values to multiple constants or variables in one row using commas:

var x = 0.0, y = 0.0, z = 0.0

Exercise:

Use the let keyword to declare a constant to save the value that will not be changed in the Code. Use the var keyword to save the value that needs to be changed in the code.

Type ID

A type identifier is provided when a constant or variable is declared to specify the type of the value that can be saved by the constant or variable. In use, a colon is followed by a constant or variable name, and a space is followed by the type name to be used:

1 var welcomeMessage: String

The colon indicates "the type of... is..." in the declaration. Therefore, the code in the above example indicates: "The type of the variable welcomeMessage is String ".

"String type" means that "value of any String type" can be saved, that is, "the type of things (or the type of things)" that can be stored )".

The variable welcomeMessage can now save values of any string type without the following error:

1 welcomeMessage = "Hello"

Note:

In practice, type identifiers are rare. If you provide an initial value when defining a constant or variable, Swift can generally infer the type that the constant or variable should use. For more information, see type security and type inference (which will be translated later ). In the preceding welcomeMessage example, the initial value is not provided. Therefore, the type is explicitly specified for the welcomeMessage variable through the type description, instead of being inferred from the initial value.

 

Constant and variable naming

You can use almost any character to name constants or variables, including Unicode characters:

1 let π = 3.141592 let Hello = "Hello World" 3 let
= "Dogcow

Constants and variable names cannot contain mathematical symbols, arrows, private (invalid) Unicode code numbers, or characters used to draw lines/boxes. The name cannot start with a number, but it can be used in other places except for the start.

Once you declare a constant or variable with a specified value type, you cannot re-declare a constant or variable with the same name for it, it cannot be changed to store different types of values, nor can it be declared as a variable again, and the variable is declared as a constant again.

Note:

If you need to name a constant or variable as a reserved word of Swift, You can enclose the reserved word as a name using reverse quotation marks. However, you should avoid using reserved words as names unless you are forced to use them.

You can change the value of the variable to another value of the same type. In the following example, the value of the variable friendlyWelcome is changed from "hello !" Change to "Bonjour !" :

1 var friendlyWelcome = "Hello! "2 friendlyWelcome =" Bonjour! "3 // The value of friendlyWelcome is" Bonjour! "
 

Unlike variables, constants cannot be changed once assigned values. An error will be reported when you try to change the code. The following code will report an error during compilation:

1 let Your agename = "Swift" 2 your agename = "Swift ++" 3 // compile an error-Your agename cannot be changed
 

Constant and variableOutput

Use the printIn function to output the current values of constants and variables:

1 println (friendlyWelcome) 2 // output "Bonjour !"

Println is a global function that outputs a value and returns a line break at the end. For example, during development in Xcode, println outputs the output content to the "console" Panel of Xcode. (Another function print performs almost the same operation. The difference is that the latter does not wrap the line at the end of the output value .)

Similar to the NSLog function of Cocoa, println can also output more complex log messages. The message content can contain the current value of a constant or variable.

Swift uses string interpolation to add a constant or variable name to a long string as a placeholder, prompting Swift to replace these placeholders with the value of the current constant or variable. Put the constant or variable name into the backslash and add a pair of parentheses --"\()":

1 println ("The current value of friendlyWelcome is \ (friendlyWelcome)") 2 // output "The current value of friendlyWelcome is Bonjour !"

Note:

For all the options available for string insertion, see string insertion (translated in subsequent chapters)

 

Thank you, Swifter-QQ group: 362232993 ~

Fork: https://github.com/Joejo/Swift-lesson-for-chinese

 

 

 

 

 

 

 

 

 

 

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.