Defined
letDefines constants that are not allowed to be modified once assigned
varDefine variables that can still be modified after assignment
//: # 常量//: 定义常量并且直接设置数值let x = 20//: 常量数值一经设置,不能修改,以下代码会报错// x = 30//: 使用 `: 类型`,仅仅只定义类型,而没有设置数值let x1: Int//: 常量有一次设置数值的机会,以下代码没有问题,因为 x1 还没有被设置数值x1 = 30//: 一旦设置了数值之后,则不能再次修改,以下代码会报错,因为 x1 已经被设置了数值// x1 = 50//: # 变量//: 变量设置数值之后,可以继续修改数值var y = 200y = 300
Automatic derivation
- Swift can deduce the exact type of the variable according to the code on the right.
- Typically at development time, you do not need to specify the type of the variable
- If you want to specify a variable, you can use it after the variable name: And then follow the type of the variable
Important tip: Option + Click To see the types of variables
No implicit conversions!!!
- Swift is extremely strict with data type requirements
- No implicit conversions are made at any time.
If you want to perform calculations on different types of data, you must explicitly convert
let x2 = 100let y2 = 10.5let num1 = Double(x2) + y2let num2 = x2 + Int(y2)
Let & var options
- You should select constants as much as possible before you need to modify them to
var
- In Xcode 7.0, if the variable is not modified, Xcode will prompt to change to
let
Swift constants and variables