This series is a quick tutorial for those who have programming experience in other languages, and it is best to have the basics of Java or C/C++ before browsing this series. Based on this, this series will mainly compare the similarities and differences between Swift and other languages to improve the efficiency of learning. Nor does this series attempt to cover all the details of the Swift language in its entirety, leaving it to the reader to study the Swift official language manual。 As an first article, this article begins with an introduction to the methods of defining variables and constants in Swift
One of the most important features of Swift compared to traditional high-level languages is type inference,This is reflected in a program when defining a variable or constant, often without specifying its data type, and by letting the compilation system infer from the context.
Variable
The definition of variables in Swift uses the keyword “var”, such as:
1 | var a=1,b=2.9,c="string" |
In the above code, the declaration defines three variables integer type variable a floating-point type variable b string type variable c, none of which need to specify the type, but let the compilation system perform type inference
Of course, it can also be divided into three definitions:
1 | var a=1 |
Note that in Swift there is no need to follow a semicolon (“;” ) to indicate the end of the statement, unless you need to write more than one statement on a single line
In Swift, variable names can take on a variety of characters except keywords, so you can define variables as follows:
1 | //Use Chinese for variable naming |
Of course, you can also explicitly specify the data type of each variable if you want, such as:
1 | var a:Int=1,b:Float=2.9,c:String="string" |
Because the type is specified, it is also possible to not give an initial value
1 | var one,two,three:Int |
Constants
In swift, use the “let” keyword to define constants. as:
1 | let x1 = 1, x2 = 2.9, x3 = "hello" |
Constants, of course, cannot be modified in the program again, so must be assigned an initial value in the definition. Of course, you can also specify the data type explicitly, such as:
1 | let x1:Int = 1, x2:Float = 2.9, x3:String = "hello" |
Next
Next, we’ll take a brief look at data types in Swift Swift Language Tutorial for Beginner 2 - Data Type.