Swift Language Guide (i) Swift language basics: Constants and variables

Source: Internet
Author: User
Tags constant variables reserved

Swift is a new programming language for the development of IOS and OS X applications, however, its development experience has much in common with C or objective-c.

Swift provides all the underlying types in C and objective-c, including int representing integers, Double and float for floating-point numbers, bool for Boolean values, and String that represents plain text data. Swift also provides strong support for the two basic collection type Array and Dictionary, which can be referenced (collection type) Collection Types.

Like the C language, Swift uses variables to store data and to reference variable values through identifiers. Swift also expands the amount of immutable values--constants--to make it much more powerful than constants in C. Use constants to make your code more secure and concise when you operate in Swift with data that does not need to change values.

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

Swift also introduced an optional value (optional types) to handle nonexistent values. An optional value can "exist a value X", or "No value exists". Optional values are similar to objective-c for pointers, but can be used on any type, not just classes, in Swift Nil. Optional values are more secure and semantically more vivid than Objective-c's nil pointers, and are used in depth in many of Swift's most powerful functions.

An optional value is a manifestation of Swift's type safety. Swift can help you get a clear picture of the types of data that your code can handle. If the code wants to get a String type, the type-safe attribute will prevent you from incorrectly passing the INT type. This allows you to discover and fix problems as early as possible during the development process.

Constants and variables

Constants and variables associate names (such as maximumnumberofloginattempts or welcomemessage) with a particular type of value, such as Number 10 or string "Hello". Once a constant is assigned a value, its value cannot be changed, and the variable can be assigned a value later.

Declarations of constants and variables

Constants and variables must be declared separately using the Let keyword and the var keyword, and the following example shows how constants and variables track the user's logon times:

1 Let maximumnumberofloginattempts = 10
2 var currentloginattempt = 0

The code in the example above can be interpreted as declaring a constant named maximumnumberofloginattempts and assigning a value of 10. Declares a variable currentloginattempt and initializes its value to 0.

The maximum number of times a user is allowed to attempt to log on is assigned a constant because the maximum number of times is unchanged at run time, and the current login count is assigned to a variable, because the number of attempts to log on to the current failure is cumulative.

You can complete multiple constants or variable assignments in a single line by using a comma-delimited method:
var x = 0.0, y = 0.0, z = 0.0

Practice:

Declare a constant with the Let keyword to save values that will not be changed in your code, and use the var keyword to save the values you need to change in your code

Type identification

Declaring a constant or variable provides the type identity at all times to specify the type of value that the constant or variable can hold. Use the following constant or variable name with a colon, a space, plus the type name to use:

1 var welcomemessage:string

The colon indicates in the declaration "... Type is ... ", so the code in the example above means:" The type of the variable welcomemessage is string. "

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/extra/

String type means that you can save "any string value", that is, the type of thing (or kind of thing) that can be stored.

Variable welcomemessage can now save the value of any string type without an error:

1 welcomemessage = "Hello"

Note:

It is very rare to have a type identification in practice. If you provide an initial value when defining a constant or variable, Swift can usually infer the type that the constant or variable should use, as detailed in type safety and type inference (later chapter translation). In the above Welcomemessage example, the initial value is not provided, so the type description is given to the welcomemessage variable explicitly, without having it inferred from the initial value.

Constants and the naming of variables

You can use almost any character to name a constant or variable, including Unicode characters:

letπ= 3.14159 let  
hello = "Hello World"
let   
     
= "Dogcow

The names of constants and variables may not contain mathematical symbols, arrows, private (that is, invalid) Unicode code numbers, or the characters used to draw lines/boxes. And the name cannot start with a number, but the number can be used in addition to the other places at the beginning.

Once you declare a constant or variable that specifies a value type, you cannot again declare a constant or variable of the same name to it, or change it to hold a different type of value, not to declare a constant as a variable, and a variable again as a constant.

Note:

If you need to name a constant or variable as Swift's reserved word, you can surround it with an inverted quotation mark (') when you use the reserved word as a name. Still, you should avoid using reserved words as names unless you are forced to.

You can change the value of a variable to another value of the same type, in the following example, the value of the variable friendlywelcome by "hello!" Become "bonjour!" :

1 var friendlywelcome = "Hello!"
2 Friendlywelcome = "bonjour!"
The value of 3//friendlywelcome is now "bonjour!"

Unlike a variable, a constant cannot be changed once it is assigned a value. Attempting the change will cause an error, and the following code will have an error when compiling:

1 Let LanguageName = "Swift"
2 LanguageName = "swift++"
3//Compile times Error-LanguageName cannot be changed

Output of constants and variables

To output the current values of constants and variables through the Printin function:

1 println (Friendlywelcome)
2//Output "bonjour!"

PRINTLN is a global function that outputs a value and then lines a newline character at the end. For example, in Xcode environment development, println outputs output to the console panel of Xcode. (Another function print performs almost the same operation, except that the latter does not wrap at the end of the output value.) )

Similar to the NSLog function of Cocoa, println also outputs more complex log messages, which can contain the current values of constants or variables.

Swift adds a constant name or variable name as a placeholder to a long string using string interpolation, prompting Swift to replace these placeholders with the values of the current constant or variable. Place a constant or variable name in a backslash alphanumeric pair of parentheses-"\ ()":

1 println ("The current value of Friendlywelcome is \ (friendlywelcome)")
2//Output "The current value of Friendlywelcome is bonjour!"

Note:

String inserts all available options see string Insertion (later chapter translation)

Author: cnblogs Joe.huang

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.