Preface
Recently, I am learning Swift, which is actually very easy for iOS developers who are proficient in OC programming, but Swift has indeed changed a lot in terms of syntax and programming habits. It may be difficult for novices who have never understood OC language and started learning iOS development from Swift. Below I will combine the learning results of this period to make a simple summary of the knowledge I searched online, hoping that it can help friends who are learning Swift.
Definition of variables and constants
Swift development documentationThe variables and constants are defined in this way: constants and variables associate names with values of a specific type. Once the value of a constant is set, it cannot be changed anymore, but the variable can be set to different values in the future (see the name of "Knowledge", it's very simple)
How to declare variable constants
Constants and variables must be declared before use, the keyword let is used to declare constants, and the keyword var is used to declare variables. Let's give a simple example:
class Person: NSObject { let life = 1 var age = 0 }
Here we have a Person class that inherits NSObject. Obviously, there is only one constant in a person's life that should be set to an unchangeable constant, but the age of a person changes over time should be declared as a variable. Similarly, when you have similar requirements during the development process, you should choose when to use variables and when to use constants in this way.
Of course, we can choose a line of code to declare multiple simple variables or constants in a comma-separated form as follows:
var a = 0, b = 1.0, c = "CoderYQ"
I need to explain about it hereType safety and type inference in Swift. Swift is a type-safe language, that is, you must always be clear about the type of value that the code needs to process at this time.The compiler will perform type checking, and any mismatched types will be marked as errors, of course, it cannot participate in the operation.. Type checking can help you avoid errors when you manipulate different types of values. Of course, not all variables and constants need to specify a certain type. If you do not specify a type for the declared variable or constant,Swift will use the function of type inference to infer appropriate types. By checking the value you assign to the variable, type inference can automatically infer the type of value during the compilation stage. This is the type inference in Swift.. Just like in the above code that continuously declares variables a, b, and c, we do not clearly point out the types of a, b, and c, the compiler infers that the types of a, b, and c are: Int type, Double type, and String type by the values you assign to a, b, and c.
But at some necessary moments, we need to provide type annotations to declared variables or constants to clarify the values they can store. The method to add type annotation is to add a colon after the name of a variable or constant, then a space, and finally add the type name to use (it is different from OC here, so everyone needs to adapt). The following code effect is actually the same as the above:
var a: Int = 0 var b: Double = 1.0 var c: String = "CoderYQ"
If the types of variables are the same, we can also declare it like this:
var a, b, c : Double
Naming of variables and constants
The names of constants and variables can use almost any character, even Unicode characters:
let π = 3.14159 let Hello = "Hello World" let 🐶🐮 = "dog cow"
But one thing to note: constants and variable names cannot be includedWhitespace characters、Mathematical symbols、arrow、Reserved (or invalid) Unicode code bits、ConnectingandTab symbols. Can'tStart with numbers, although numbers can be used almost anywhere else in the name. Once you declare a constant or variable of a certain type, you cannot declare it again with the same name, nor can you let it save other types of values instead. Constants and variables are also not interchangeable. If you need to use Swift-preserved keywords to name a constant or variable, you can use backticks ( ` ) to surround it as the name. Anyway, unless there is no choice, avoid using keywords as names unless you really have no choice (quoted from document translation, nothing to say...).
To sum up: The naming of variables and constants in Swift is more flexible and changeable than in OC, but there are still the above provisions that need to be paid attention to, and their naming is as good as possible to facilitate collaborative cooperation among developers. Here I will list the main keywords in Swift for you, and I hope you will try to avoid them when naming them.
Keywords used as 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 as expressions and types:
as、dynamicType、is、new、super、self、Self、Type、__COLUMN__、__FILE__、__FUNCTION__、__LINE__
Keywords that are preserved in a specific 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 variable constants
After learning above, we have become proficient in using constants and variables. So what is the essential difference between constants and variables? Here are examples:
//Create a UIView object through the UIView() method (assuming that the memory address allocated by the system is: 0x7faa31616bb0) and assign it to a constant declared as UIView type: view0let view0 : UIView = UIView() //Create another UIView object through the UIView() method (assuming that the memory address allocated by the system is: 0x7f9890c062b0) and assign it to the variable declared as UIView type: view1var view1 : UIView = UIView()
The meaning of the first line of code: First, create an object of UIView type with memory address 0x7faa31616bb0 in the heap area in the memory, and then declare a constant named view0 in the stack area in the memory to point to the object, that is, the address 0x7faa31616bb0 is saved in view0, and the value of the constant is immutable (Isn't this nonsense), that is, the memory address saved in view0 cannot change.
The meaning of the second line of code: Create a new UIView type object with a memory address of 0x7f9890c062b0 in the heap area, and then declare a variable named view1 in the stack area to point to the object, that is, the address 0x7faa31616bb0 is saved in view0. Note that the value of view1 can be changed at this time, that is, the memory address saved in view1 can be changed.
If you perform the following operation at this time:
//Recreate a new UIView object (assuming the memory address allocated by the system is: 0x7f9890c042b0) and assign it to the above constant view0view0 = UIView()
The compiler will report such an error:
error: cannot assign to value: 'view0' is a 'let' constant,change 'let' to 'var' to make it mutable
It is mainly because the new object created has a new memory address. You reassign the new object to view0, that is, view0 now points to another object, which is equivalent to modifying the original stored 0x7faa31616bb0 memory address in view0 to 0x7f9890c042b0, but once the memory address stored in view0 is assigned, it cannot be modified, so the compiler reports an error here. He suggests that you change let to var to declare view0
//Recreate a new UIView object (assuming the memory address allocated by the system is: 0x7f9890c042b0) and assign it to the above variable view1view1 = UIView()
There will be no errors here, because the memory address saved in view1 can be modified.
But if I continue to execute the following code, will the compiler report an error?
= =
The meaning of the two codes: first set the background color of view0 to white, and then change the background color of view0 to black (Swift2.0 and Swift3.0 are different in the way to modify the background color. Swift3.0 is used here, but the code is simplified, and there is no essential difference)
The answer is no, because in the above operation, I did not modify the memory address saved in view0, but just got the object pointed to by view0 through the memory address saved in view0, and then modified the properties inside the object (here is backgroundColor, it can also be frame, etc.), which has nothing to do with whether view0 is a constant or a variable.
Summarize
The essence of the value of a constant is that the memory address it saves cannot be modified, but the object pointed to by the address can be obtained and the attributes of the object are modified.
The essence of the value of a variable can be modified is that the memory address it saves can be modified.
Okay, the above is the entire content of this article. I hope the content of this article will be of some help to everyone's study or work. If you have any questions, you can leave a message to communicate.