Swift variable and constant, Swift variable
Apple launched swift for a while, and a lot of information appeared on the Internet. Thank you very much.
The Swift syntax differs greatly from the OC syntax. In the OC, we create a class and generate a class at the same time. h file and one. m file, but only one in Swift. swift file.
The syntax difference is also large, such as constants and variables:
var a = 1
Defined by var, a is the variable name and 1 is the value. To change the value of a, you only need:
a = 2
Note that you do not need to write ";" in the swift language.
Swift has a type inference. a is actually an Int type, but it can be omitted or not omitted:
var a: Int = 1a = 2
Var is used to declare a variable. If you need to declare a constant, you need to use let to declare it:
let b = 3
B is a variable and cannot change its value at this time.
The swift name does not need to comply with the identifiers. The name can be unicode encoded. That is to say, when we declare a variable or constant, we can use Chinese as the variable name.
Var china = "china"
"China" is a variable name, and the program will not report an error.
Type conversion:
var interValue = 10var doubleValue = 9.0doubleValue = Double(interValue)println(doubleValue)
Swift does not support implicit type conversion. It is also necessary to force type conversion for security reasons,
To force type conversion, you must add the conversion type before the converted value, and then add brackets, as shown in the code above:
Tuples:
Tuples combines multiple values into a compound value. The value in the meta-group can be of any type, and it is not required to be of the same type.
For example:
("age", 18)
This is a tuples with values of any type and order;
You can break down the values of tuples into independent variables/constants for use:
let stu = ("age", 18)println(stu.0)println(stu.1)
The output in the background is:
Stu.0 indicates the first value of the tuples, stu.1 indicates the second value of the tuples, And the subscript starts from 0;
We can add a label to each of the tuples. In this way, we can directly use the label:
let stu = (a: "age", b: 18)println(stu.a)println(stu.b)
The output remains unchanged;
If we only need to use a portion of the values of the tuples, we can replace the portion to be ignored "_".
let (a, _, _) = stu
You are welcome to learn from each other.