Introduction
Swift is a new language for developing iOS, OS X and watchOS applications. However, if you have C or Objective-C development experience, you will find that a lot of Swift is familiar to you.
Swift includes all the basic data types in C and Objective-C. Int is an integer value; Double and Float are floating-point values; Bool is a Boolean value; String is text data. Swift also provides three basic collection types, Array, Set, and Dictionary. See Collection Types for details.
Just like C, Swift uses variables to store and associate values with variable names. In Swift, immutable variables are widely used. They are constants and are more powerful than C constants. In Swift, if the value you want to process doesn't need to change, using constants can make your code safer and express your intentions more clearly.
In addition to the types we are familiar with, Swift adds higher-order data types such as Tuples that are not available in Objective-C. Tuples allow you to create or pass a set of data, such as a function return value, you can use a tuple to return multiple values.
Swift also adds an Optional type to handle missing values. Optional means "there is a value there and it is equal to x" or "there is no value there". Optional is a bit like using nil in Objective-C, but it can be used on any type, not just classes. Optional types are safer and more expressive than nil pointers in Objective-C, and are an important part of many of Swift's powerful features.
Swift is a type-safe language, and optional types are a good example. Swift lets you know the type of values clearly. If your code expects a String, type safety will prevent you from accidentally passing in an Int. You can find and fix errors early in the development phase.
Constants and variables
Constants and variables associate a name (such as maximumNumberOfLoginAttempts or welcomeMessage) with a value of a specified type (such as the number 10 or the string "Hello"). The value of a constant cannot be changed once it is set, and the value of a variable can be changed at will.
Declare constants and variables
Constants and variables must be declared before use, let's declare constants, and var to declare variables. The following example shows how to use constants and variables to record the number of times a user attempts to log in:
let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0
These two lines of code can be understood as:
"Declare a new constant named maximumNumberOfLoginAttempts and give it a value of 10. Then, declare a variable named currentLoginAttempt and initialize its value to 0."
In this example, the maximum number of login attempts allowed is declared as a constant because this value does not change. The current number of login attempts is declared as a variable, because this value needs to be increased each time a login attempt fails.
You can declare multiple constants or variables on one line, separated by commas:
var x = 0.0, y = 0.0, z = 0.0
note:
If you have a value in your code that does not need to be changed, use the let keyword to declare it as a constant. Declare only the values that need to be changed as variables.
Type annotation
When you declare a constant or variable, you can add a type annotation to indicate the type of the value to be stored in the constant or variable. If you want to add a type annotation, you need to add a colon and space after the constant or variable name, and then add the type name.
This example adds a type annotation to the welcomeMessage variable, indicating that this variable can store a value of type String:
var welcomeMessage: String
The colon in the declaration stands for "is ... type", so this line of code can be interpreted as:
"Declare a variable of type String and name welcomeMessage."
"Type is String" means "can store any value of String type."
The welcomeMessage variable can now be set to any string:
welcomeMessage = "Hello"
You can define multiple variables of the same type in a single line, separated by commas, and add type annotations after the last variable name:
var red, green, blue: Double
note:
In general you rarely need to write type annotations. If you assign an initial value when declaring a constant or variable, Swift can infer the type of the constant or variable, please refer to type safety and type inference. In the above example, there is no initial value assigned to welcomeMessage, so the type of variable welcomeMessage is specified by a type annotation, not inferred from the initial value.
Naming of constants and variables
You can use any characters you like as constant and variable names, including Unicode characters:
let π = 3.14159
let hello = "hello world"
let ???? = "dogcow"
Constant and variable names cannot contain mathematical symbols, arrows, reserved (or illegal) Unicode code points, wiring, and tabs. Nor can it begin with a number, but you can include numbers elsewhere in constant and variable names.
Once you declare a constant or variable of a certain type, you cannot declare it again with the same name, or change the type of value it stores. At the same time, you cannot convert constants to variables.
note:
If you need to use the same name as a Swift reserved keyword as a constant or variable name, you can use backticks (`) to surround the keyword as a name. In any case, you should avoid using keywords as constant or variable names unless you have no choice.
You can change existing variables to other values of the same type. In the following example, the value of friendlyWelcome has been changed from "Hello!" To "Bonjour!":
var friendlyWelcome = "Hello!"
friendlyWelcome = "Bonjour!"
// friendlyWelcome is now "Bonjour!"
Unlike variables, the value of a constant cannot be changed once it has been determined. Attempting to do so will result in an error when compiling:
let languageName = "Swift"
languageName = "Swift ++"
// This will report a compile-time error-languageName cannot be changed
Output constants and variables
You can use the print (_ :) function to output the value of the current constant or variable:
print (friendlyWelcome)
// print "Bonjour!"
print (:) is a global function for output, and the output will wrap at the end. If you use Xcode, print (:) will output the content to the "console" panel. (Another function is called print (_: appendNewline :). The only difference is that the output will not wrap at the end.)
The print (_ :) function outputs the passed String value:
print ("This is a string")
// print "This is a string"
The print (_ :) function can output more complex information. This information can include the values of current constants and variables.
Swift uses string interpolation to add constant names or variable names as placeholders to long strings. Swift replaces these placeholders with the current constant or variable value. Put the constant or variable name in parentheses and escape it with a backslash before the opening parenthesis:
print ("The current value of friendlyWelcome is \ (friendlyWelcome)")
// Output "The current value of friendlyWelcome is Bonjour!
note:
For all available options for string interpolation, see String interpolation.
Comment
Please comment the non-executive text in your code as a prompt or a note for your future reading. The Swift compiler will automatically ignore comments when compiling code.
Comments in Swift are very similar to comments in C. Single-line comments start with a double forward slash (//):
// this is a comment
You can also make multi-line comments, starting with a single forward slash followed by an asterisk (/) and ending with an asterisk followed by a single forward slash (/):
/* This is an,
Multi-line comments * /
Unlike C multi-line comments, Swift multi-line comments can be nested within other multi-line comments. You can generate a multi-line comment block first, and then nest a second multi-line comment within this block. When terminating a comment, insert the end tag of the second comment block, and then insert the end tag of the first comment block:
/ * This is the beginning of the first multiline comment
/ * This is the second nested multiline comment * /
This is the end of the first multiline comment * /
By using nested multi-line comments, you can quickly and easily comment out a large piece of code, even if the code already contains multi-line comment blocks.
semicolon
Unlike most other programming languages, Swift does not mandate that you use a semicolon (;) at the end of each statement, but you can add semicolons as you like. There is a case where you must use a semicolon, that is, you intend to write multiple independent statements on the same line:
let cat = "??"; print (cat)
// print "??"
Integer
Integers are numbers without decimal parts, such as 42 and -23. Integers can be signed (positive, negative, zero) or unsigned (positive, zero).
Swift provides signed, unsigned integer types of 8, 16, 32, and 64 bits. These integer types are similar to the C language, for example, 8-bit unsigned integer type is UInt8, and 32-bit signed integer type is Int32. Like other types in Swift, integer types are capitalized.
Integer range
You can access the min and max properties of different integer types to get the maximum and minimum values of the corresponding types:
let minValue = UInt8.min // minValue is 0, which is UInt8 type
let maxValue = UInt8.max // maxValue is 255, which is of type UInt8
The type of the value returned by min and max is exactly the integer type they correspond to (such as UInt8 in the above example, the type returned is UInt8), which can be used next to the same type value in the expression.
Int
In general, you don't need to specify the length of the integer specifically. Swift provides a special integer type Int, which is the same length as the native word length of the current platform:
On 32-bit platforms, Int and Int32 are the same length.
On 64-bit platforms, Int and Int64 are the same length.
Unless you need integers of a certain length, using Int is generally sufficient. This can improve code consistency and reusability. Even on 32-bit platforms, Int can store integers ranging from -2147483648 to 2147483647, which is usually large enough.
UInt
Swift also provides a special unsigned UInt that is the same length as the native word length of the current platform:
On 32-bit platforms, UInt and UInt32 are the same length.
On 64-bit platforms, UInt and UInt64 are the same length.
note:
Try not to use UInt unless you really need to store an unsigned integer with the same word length as the current platform native. Except in this case, it is better to use Int, even if the value you want to store is known to be non-negative. Using Int uniformly can improve the reusability of the code, avoid the conversion between different types of numbers, and match the type inference of numbers, please refer to type safety and type inference.
Floating point number
Floating point numbers are numbers with decimal parts, such as 3.14159, 0.1, and -273.15.
Floating point types have a larger range than integer types, and can store larger or smaller numbers than Int types. Swift provides two types of signed floating-point numbers:
Double represents a 64-bit floating point number. Use this type when you need to store large or high precision floating point numbers.
Float represents a 32-bit floating point number. This type can be used if accuracy is not high.
note:
Double is highly accurate, with at least 15 digits, while Float has at least 6 digits. Which type you choose depends on the range of values your code needs to handle.
Type safety and type inference
Swift is a type safe language. A type-safe language lets you know exactly what type of value your code is going to handle. If your code requires a String, you can never accidentally pass in an Int.
Because Swift is type-safe, it performs type checks when compiling your code and flags mismatched types as errors. This allows you to find and fix errors early in your development.
Type checking can help you avoid errors when you are dealing with different types of values. However, this is not to say that you need to explicitly specify the type each time you declare constants and variables. If you don't specify the type explicitly, Swift will use_Type inference to choose the appropriate type. With type inference, the compiler can automatically infer the type of an expression when compiling code. The principle is simple, just check the value you assign.
Because of type inference, Swift rarely needs to declare types compared to C or Objective-C. Although constants and variables need to be explicitly typed, most of the work does not need to be done by yourself.
Type inference is very useful when you declare constants or variables and assign initial values. Constants or variables can be type-inferred when you assign them a literal value (literal value or literal) when declaring them. (Literals are values that appear directly in your code, such as 42 and 3.14159.)
For example, if you assign a new constant a value of 42 without specifying the type, Swift can infer that the constant type is Int, because the initial value you assign to it looks like an integer:
let meaningOfLife = 42
// meaningOfLife is assumed to be of type Int
Similarly, if you don't specify a type for a floating-point literal, Swift will infer that you want Double:
let pi = 3.14159
// pi will be inferred to be of type Double
When inferring the type of a floating-point number, Swift always chooses Double over Float.
If both integer and floating-point numbers appear in the expression, they are inferred to be of type Double:
let anotherPi = 3 + 0.14159
// anotherPi will be presumed to be of type Double
The primitive value 3 has no explicitly declared type, and a floating-point literal appears in the expression, so the expression is inferred to be of type Double.
To be continued!
References:
The Swift Programming Language
Copyright statement: This article is an original article by the blogger and may not be reproduced without the permission of the blogger.
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.