概览
常量
- 只能赋值一次;
- 它的值不要求在编译时确定,但在使用之前必须赋值一次;
let age1 = 10
let age2: Int
age2 = 20
func getAge() -> Int {
return 30
}
let age3 = getAge()
-
下面代码是错误的
image.png
-
常量,变量在初始化之前,都不能使用
image.png
标识符
- 标识符(比常量名,变量名,函数名)几乎可以使用任何字符
- 标识符不能以数字开头,不能包含空白字符,制表符,箭头等字符
func 🐂🍺() {
print("6666")
}
🐂🍺()
let 👽 = "ET"
let 🥛 = "milk"
常见数据类型

-
整数类型: Int8、Int16、Int32、Int64、UInt8、UInt16、UInt32、UInt64
-
在32bit平台上,Int等于Int32;在64bit平台,Int等于Int64;
-
整数的最值:UInt8.max, Int16.min
-
一般情况下用Int即可
-
浮点类型:Float 32位,精度只有6位;Double,64位,精度只有15位;
let letFloat: Float = 20.0
let letDouble = 20.0
字面量
//布尔
let bool = true
//字符串
let string = "张三丰"
//字符(可存储ASCII字符、Unicode字符)
let character: Character = "🐂"
//整数
let intDecimal = 66
//浮点数
let doubleDecimal = 66.0
//数组
let array = [1,3,5,7,9]
//字典
let dictionary = ["age":18, "height":168]
类型转换
整数转换
let int1: UInt16 = 2_000
let int2: UInt8 = 1
let int3 = int1 + UInt16(int2)
整数、浮点数转换
let int = 3
let double = 0.14159
let pi = Double(int) + double
let intPi = Int(pi)
字面量可以直接相加,因为字面量本身没有明确的类型
let result = 3 + 0.14159
元祖
let http404Error = (404, "not found")
print("the status code is \(http404Error.0)")
let http200Status = (statusCode:200, description: "OK")
print("the status code is \(http200Status.statusCode)")
let (statusCode, statusMessage) = http404Error
print("the status code is\(statusCode)")
let (justTheStatusCode, _) = http404Error
网友评论