Swift is a type-safe language, and the type-safe language requires a very clear type of value in the code. If you have a partial value in your code that requires a string type, you cannot pass int incorrectly.
Given Swift's type safety, when compiling code, Swift performs type checking and marks any type mismatch as an error, allowing you to catch and fix errors as early as possible in development.
Type checking helps you avoid making mistakes when manipulating different types of values. But that doesn't mean you have to check the type when declaring every constant or variable, and if you don't check the type of value you want, Swift performs type inference to calculate the appropriate type.
Type inference allows the compiler to automatically infer the type of a particular expression, based on the value you provide, when compiling the code.
Based on type inference, Swift requires much less of a type declaration than a C or objective-c language. Constants and variables still have a definite type, but the work of specifying the type explicitly is done by the compiler on your behalf.
Type judgment is especially useful when you declare a constant or variable and give an initial value. It is usually implemented (type judgment) by assigning a literal value (literal value, or "literal" literal) at the time of the Declaration. (literals refer to values that appear directly in the source code, 42 and 3.14159 in the following example)
For example, if you give a new constant a literal value of 42 but do not specify its type, Swift will infer that you want a constant of type int because the number you provide when initializing is like an integer:
1 Let Meaningoflife = 42
2//Meaningoflife is inferred to be int type
Similarly, if you do not specify a type for floating-point literals, Swift infers that you want to create a double type:
1 Let pi = 3.14159
2//pi is inferred as double type
Swift usually uses a double instead of float when inferring floating-point numbers.
If you combine integers and floating-point literals in an expression, Swift returns the double as inferred from the context:
1 Let Anotherpi = 3 + 0.14159
2//Anotherpi will be inferred as double type
In the example above, literal 3 itself is not a type, nor is it explicitly specified, and the double type is inferred and appropriately printed based on the floating-point number literal of the currently attached portion.
Author: cnblogs Joe.huang
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/extra/