The added type in swift: tuple (tuples) allows you to create or transmit a group of data,
For example, when you return a function value, you can use a single tuple to return multiple values.
The optional (Optional) Type is added to swift to handle missing values.
(Optional) "there is a value and it is equal to X" or "there is no value ".
Optional is a bit like using nil in OC, but it can be used on any type, not just a class.
The optional type is safer and more expressive than the NIL pointer in OC.
Constants and variables must be declared before use
Constant: Let maxnum = 10
Variable: var currentnum = 50
VaR x = 0.0, y = 0.0, Z = 0.0
Type annotation:
VaR welcomemessage: String
Welcomemessage = "Hello Swift"
Note: Generally, 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 this constant or variable. For details, refer to type security and type inference.
In the preceding example, no initial value is assigned to welcomemessage,
Therefore, the type of the welcomemessage variable is specified by a type annotation,
It is not inferred from the initial value.
Constant and variable naming
You can use any character as the constant or variable name.
Run n = 3.14
Let Hello = "Hello Swift"
Let ???? = "Swift good"
Note: constants and variables cannot contain mathematical symbols, arrows, and reserved (or invalid) Unicode codes,
Link and tab. It cannot start with a number, but it can contain numbers elsewhere in the constant and variable name.
Note: If you need to use the same name as the SWIFT reserved keyword as the constant or variable name,
You can use this keyword as the name by using the reverse quotation mark.
In any case, you should avoid using keywords as constants or variable names unless you have no choice.
Value can be changed
VaR feiendly = "Hello! "
Friendly = "Swift ++! "OK
Let LAN = "Swift +"
The LAN = "Swift ++" error compiler reports an error
Output constants and variables
The output content of printfin (constant or variable name) will wrap at the end
Print (constant or variable name) Output content will not wrap at the end
Printin ("this is a string! ")
Placeholder output
VaR name = "Tom"
Printin ("the named is \ (name )")
Note:
Single line comment ://
Multi-line comment:/* Comment content */
Multi-line comments include multi-line comments /*/**/*/
Each swift statement can be followed by ";", but it must be written in the same row.
Write multiple independent statements.
Let cat = "??? "; Printin (CAT)
Integer:
Value Range: Let minvalue = uint8.min uint8. The minimum value is 0.
Let maxvalue = uint8.max uint8 type maximum 255
Int
In general, you do not need to specify the length of an integer. Swift provides a special Integer type int,
The length is the same as the native font length of the current platform.
-On a 32-bit platform, int and int32 are of the same length.
-On a 64-bit platform, int and int64 are of the same length.
Uint
Swift also provides a special unsigned uint with the same length as the native character of the current platform.
-On a 32-bit platform, uint and uint32 are of the same length.
-On a 64-bit platform, uint and uint64 are of the same length.
Try not to use uint: Using int in a unified manner can improve code reusability,
Avoid conversion between different types of numbers,
And the Type Estimation of matching numbers
Floating Point Number
Number with decimals, 20.36, 0.35
Double indicates a 64-bit floating point number.
Float indicates a 32-bit floating point number.
Note: The double type is highly accurate and has at least 15 digits, while float has at least 6 digits.
The type you select depends on the range of values to be processed by your code.
Type speculation
Let meaningof = 42
Meaningof is inferred to be int type
Lets Pi = 3.14159
Pi is assumed to be of the double type.
When we speculate on the floating point type, swift always chooses double instead of float.
If the expression contains both integers and floating-point numbers, it is assumed to be of the double type:
Let Mun = 3.14159 +
Numeric type conversion
Let two: uint16 = 2;
Let one: uint8 = 1;
Let onetwo = two + uint16 (one)
Integer and floating point conversion
The integer and floating point numbers must be converted to the specified type.
Let three = 3
Letting point = 0.259
Let Pi = double (three) + point
Let inter = int (point)
Type alias: defines a name for an existing type. (Typelias)
Typelias audio = uint16
VaR maxamp = audio. Min
Boolean Value
Swift has two Boolean bright, true or false
Let one = true;
Let two = flase;
If one
{
Printin ("this is true! ");
}
Else
{
Printin ("this is false! ");
}
Let I = 1
If I
{
/// The program reports an error
}
Let I = 1
If I = 1
{
/// The program does not report an error
}
Tuples
Combine multiple values into one conformity value. The values in the element group can be of any type,
It is not required to be of the same type.
Let httperror = (404, "not found ")
It can be described as a tuples of the (INT, string) type.
You can break down the content of a tuples (decompose) into separate constants and variables,
Then you can use them normally:
Let (statuscode, statusmessage) = httperror
Printin ("the status code is \ (statuscode )")
Printin ("the status message is \ (statusmessage )")
If you only need a part of the tuples,
During decomposition, you can mark the parts to be ignored with underscores:
Let (statuscode, _) = httperror
Printin ("ths status code is \ (statuscode )")
In addition, you can use subscript to access a single element in the tuples. The subscript starts from scratch:
Printin ("the status code is \ (httperror.0 )")
Printin ("the status message is \ (httperror.1 )")
You can name a single element when defining the tuples:
Let http200 = (statuscode: 200, Description: "OK ")
Printin ("the status code is \ (http200.statuscode )")
Printin ("the description is \ (http200.description )")
Optional
Use optional values to handle possible missing values.
Note: C and objective-C do not have the optional concept.
The closest is a feature in objective-C,
If a method does not return an object or nil, nil indicates "a valid object is missing ".
However, this only applies to objects-for struct,
The basic C type or enumeration type does not work.
For these types, the objective-C method generally returns
Special values (such as nsnotfound) indicate missing values.
This method assumes that the caller of the method knows and remembers to judge the special value.
However, the swift option allows you to imply that any type of value is missing without a special value.
The following example uses the toint method to convert a string to an int.
Let number1 = "123"
Let convernum = number. toint ()
Because the toint method may fail, it returns an optional (optional) int,
Instead of an int.
An optional int is written as an int? Instead of Int.
The question mark implies that the included value is optional, that is, it may contain an int value or not.
(It cannot contain any other value, such as a bool value or a string value. It can only be Int or nothing .)
If statement and forced resolution
You can use the if statement to determine whether an optional value is included.
If the value is optional, the result is true. If there is no value, the result is false.
After you confirm that the optional package does contain values,
You can add an exclamation point (!) after an optional name (!) To obtain the value.
This exclamation point indicates "I know this option has a value. Please use it.
This is called mandatory resolution of optional values (forced unwrapping ):
If convernum
{
Printin ("\ (numner1) has an value \ (convernum !) ")
}
Else
{
Printin ("\ (number1) can not be conver to int ")
}
Note: use! To obtain an optional value that does not exist, causing a running error.
Use! Before force resolution, you must determine whether to include a non-nil value.
Optional binding
Use the optional binding (optional binding) to determine whether the optional include values,
If it contains, the value is assigned to a temporary constant or variable.
Optional binding can be used in the IF and while statements to determine the optional values and assign the values to
Constant or variable.
If let annum = number1.toint ()
{
Printin ("\ (numner1) has an value \ (annum )")
}
Else
{
Printin ("\ (number1) can not be conver to int ")
}
This code can be understood:
"If the optional int returned by number1.toint contains a value,
Create a new constant called annum and assign the optional values to it ."
If the conversion is successful, the annum constant can be used in the first branch of the IF statement.
It has been initialized by optional included values, so it does not need to be used again! Suffix to obtain its value.
In this example, annumber is only used to output the conversion result.
Nil
You can assign an optional variable nil to indicate that it has no value.
VaR serverres: Int? = 404
Serverres = Nil
Note: Nil cannot be used for non-optional always-on and variable.
If your code is always bright or the variable needs to handle Missing Values, declare them as optional.
If you declare an optional bright or variable but do not copy it, it will be automatically set to nil
VaR Sur: string?
// Sur = Nil
Note: nil in SWIFT is not the same as nil in objective-C.
In objective-C, Nil is a pointer to a non-existent object.
In swift, Nil is not a pointer -- it is a definite value, used to indicate that the value is missing.
Any type of options can be set to nil, not just the object type.
Optional for implicit Parsing
This type of optional is defined as implicit parsing optional (implicitly unwrapped optionals ).
Use the question mark (string?) next to an optional type ?) Change to exclamation point (string !)
To declare an implicit parsing.
Let possa: string? = "This is mandatory resolution required! Value"
Printin (possa !)
Let possb: string! = "This is implicit conversion not required! "
Printin (possb)
You can use implicit parsing as an optional option for automatic parsing.
All you have to do is put the exclamation point at the end of the Type when declaring it,
Instead of the end of the optional name for each value.
Note: If you try to set a value when no value is available for implicit parsing, a running error is triggered.
It is the same as adding an exclamation point after a normal option with no value.
You can choose implicit parsing as normal to determine whether it contains values.
If possb
{
Printin (possb)
}
You can also use the implicit resolution option in the optional binding to check and parse its value:
If let defindes = possb
{
Printin (defindes)
}
Note: If a variable may become nil, do not use implicit parsing.
If you need to determine whether it is nil in the life cycle of the variable, use the normal optional type.
Assertions
Optional. You can determine whether a value exists. You can optimize the processing of missing values in the code.
However, in some cases, if the value is missing or the value does not meet specific conditions,
Your code may not need to be executed.
In this case, you can trigger an assertion in your code to end code execution.
The cause of missing values is found through debugging.
Let age =-3
Assert (age> = 0, "a person's age cannot be less than zero ")
Here, the assertion will trigger because age <0
In this example, the code runs only when age> = 0 is true,
That is, when the value of age is not negative.
If the value of age is negative, as in the code, age> = 0 is false, and the assertion is triggered,
End the application.
When to use assertions
Use assertions when conditions may be false, but in the end, make sure the conditions are true,
In this way, your code can continue to run.
Applicable scenarios of assertions:
-The index of the ancillary script of the integer is passed into a custom ancillary script implementation,
However, the subscript index value may be too small or too large. (In my own opinion, the array is out of bounds)
-You need to input a value to the function, but the invalid value may cause the function to fail to run normally.
-An optional value is now nil, but a non-nil value is required for subsequent code execution.
Note:
Assertions may cause your application to stop running,
Therefore, you should carefully design your code so that invalid conditions do not appear.
However, some illegal conditions may occur before your application is released,
In this case, assertions can be used to quickly discover problems.
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