Swift Language Tutorial for Beginner 1 - Variable and Constant

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.


The definition of variables in Swift uses the keyword “var”, such as:

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:

var a=1
var b=2.9
var c="string"

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:

//Use Chinese for variable naming
var 变量 = "变量"
//Use emojis for naming
var 😄 = "开心"
//Named with reserved keywords
var `var` = 2

Of course, you can also explicitly specify the data type of each variable if you want, such as:

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

var one,two,three:Int


In swift, use the “let” keyword to define constants. as:

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:

let x1:Int = 1, x2:Float = 2.9, x3:String = "hello"


Next, we’ll take a brief look at data types in Swift Swift Language Tutorial for Beginner 2 - Data Type.

本文标题:Swift Language Tutorial for Beginner 1 - Variable and Constant

文章作者:Morning Star

发布时间:2022年01月09日 - 10:01

最后更新:2022年01月17日 - 07:01


许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。