In depth understanding of variables and constants in Swift

  • 2020-05-27 07:19:03
  • OfStack


Swift recently in learning a new language, programming for mastering OC iOS developers actually very easy to use, but Swift on grammar and programming habits have changed a lot, for never know OC language to start learning from Swift iOS development beginners can fit one difficulty, below I will this time the learning outcome of combining the knowledge of the search on the net do a simple summary, hope you can help to friends are learning Swift.

Definition of variables and constants

Variables and constants are defined in the Swift development documentation in such a way that constants and variables associate a name with a value of a particular type. Once the value of 1 is set, it cannot be changed. However, variables can be set to different values in the future.

How do I declare a variable constant

Constants and variables must be declared before use, using the keyword let to declare constants and var to declare variables. Here's a simple example:

class Person: NSObject {
 let life = 1
 var age = 0

Here we have a class Person inheriting NSObject. Obviously, a person's life should only be set to a constant that cannot be changed, but the age of a person changes over time and should be declared as a variable. Similarly, when you have similar requirements in the development process, you should choose when to use variables and when to use constants.
Of course, we can choose 1 line of code to declare multiple simple variables or constants in comma-separated form as follows:

 var a = 0, b = 1.0, c = "CoderYQ"

Here we need to talk 1 about type security and type inference in Swift. Swift is a type-safe language, which means you must always be aware of the type of value that your code needs to handle at this point. The compiler will do type checking, and any type that doesn't match will be marked as an error, and of course it won't be used. Type checking can help you avoid errors when you manipulate different types of values. , of course, not all of the variables and constants need to be made clear that a certain type, if you don't specify types for declaration of the variable or constant, Swift features using type inference to infer the appropriate type, through the check you give the value of the variable type inference to compile phase automatically infer the types of values, this is Swift type inference. Just as we didn't specify the types of a, b, c in the code above that continuously declares the variables a, b, c, c, a, c, the compiler deduces the types of a, b, c from the values you assign to a, b, c: Int, Double, String.

But at some point we need to provide type annotations for declared variables or constants to specify the values they can store. The way to add type annotation is to add a colon and a space after the name of a variable or constant, and finally add the type name to be used (this is not the same as OC). The code effect shown below is actually the same as above:

var a: Int = 0
var b: Double = 1.0
var c: String = "CoderYQ"

If all variables are of type 1, we can also declare:

var a, b, c : Double

Names of variables and constants

Names of constants and variables can use almost any character, even the Unicode character:

let  PI.  = 3.14159
let  hello  = " Hello world "
let 🐶🐮 = "dog cow"

But note 1: the names of constants and variables must not contain white space characters, mathematical symbols, arrows, reserved (or invalid) Unicode code points, lines, and tabs. You can't start with a number either, although Numbers can be used almost anywhere else in the name. Once you declare a constant or variable of a definite type, you cannot declare it again with the same name, nor can you change it to a value of another type. Constants and variables are not interchangeable either. If you need to use the keyword reserved by Swift to name a constant or variable, you can use backquotes (') to enclose it as the name. In short, avoid using keywords as names unless you have no choice but to do so. .

The naming of variables and constants in Swift is more flexible than that in OC, but there are still the above rules that need to be paid attention to, and their naming should be as transparent as possible, so as to facilitate the collaboration between developers. Here I have listed the main keywords in Swift for you to avoid when naming them.
Keywords used for declaration:

class , deinit , enum , extension , func , import , init , let , protocol , static , struct , subscript , typealias , var

Keywords used as statements:

break , case , continue , default , do , else , fallthrough , if , in , for , return , switch , where , while

Keywords used for expressions and types:

as , dynamicType , is , new , super , self , Self , Type , __COLUMN__ , __FILE__ , __FUNCTION__ , __LINE__

Keywords that are reserved in a particular context:

associativity , didSet , get , infix , inout , left , mutating , none , nonmutating , operator , override , postfix , precedence , prefix , right , set , unowned , unowned(safe) , unowned(unsafe) , weak , willSet

The essential difference between variables and constants

After the above study, we have been able to skillfully use constants and variables, so what is the essential difference between constants and variables? Here is an example to illustrate 1:

// through  UIView()  Method to create 1 a  UIView  (suppose the memory address allocated by the system is: 0x7faa31616bb0 ) and assign the value to be declared as  UIView type   The constants: view0
let view0 : UIView = UIView()

// through  UIView()  Method creation additional 1 a  UIView  The object of ( Suppose the memory address allocated by the system is: 0x7f9890c062b0)  And assign the value to be declared as  UIView type   The variables: view1
var view1 : UIView = UIView()

The meaning of lines of code 1: in the first place in the heap memory area to create a memory address 0 x7faa31616bb0 UIView type of object, and then stack in the memory area that a constant called view0 point to the object, namely view0 0 x7faa31616bb0 is saved in the address, and the value of the constant is immutable (not all), namely view0 kept in memory address cannot be changed.

Meaning: 2 lines of code in the heap area and create a new memory address 0 x7f9890c062b0 UIView type of object, and then in the stack area that one called view1 variable pointing to the object, namely view0 0 x7faa31616bb0 is saved in the address, attention view1 values can be changed at this time, namely view1 kept in memory address can be change.

If you do the following:

 var a = 0, b = 1.0, c = "CoderYQ"

The compiler will report an error like this:

 var a = 0, b = 1.0, c = "CoderYQ"

Is mainly due to create new objects have a new memory address, you put the new object to assign a value to view0, namely view0 now pointing to another one object, the equivalent of the originally stored in view0 0 x7faa31616bb0 memory address modification is 0 x7f9890c042b0, but view0 stored in the memory address as the assignment can't be modified, so the compiler error, He suggests that you declare view0 by changing let to var

 var a = 0, b = 1.0, c = "CoderYQ"

There is no error because the memory address saved in view1 can be modified.

But if I then execute the following code, will the compiler report an error?

view0.backgroundColor = UIColor.white
view0.backgroundColor =

First, the background color of view0 is set to white, and then the background color of view0 is changed to black. (the background color of Swift2.0 and Swift3.0 are modified in different ways. Here, Swift3.0 is used.

The answer is no, because in the above operation, I did not change the memory address saved in view0, but I only took the object pointed to by view0 through the memory address saved in view0, and then changed the internal properties of the object (here is backgroundColor, can also be frame, etc.), which has nothing to do with whether view0 is a constant or a variable.


The unmodifiable nature of the value of a constant is that the memory address it holds is unmodifiable, but it can be used to take the object that the address points to and modify the properties of the object.

The essence of a variable's modifiable value is that its stored memory address can be modified.

Well, the above is the entire content of this article, I hope the content of this article to your study or work can bring 1 definite help, if you have questions you can leave a message to communicate.

Related articles: