常量
只能赋值一次
let age: Int
age = 20
它的值不要求在编译时确定,但使用之前必须赋值一次
var num = 10
num += 20
num += 30
let age2 = num
func getAge() -> Int{
return 10
}
let age = getAge()
print(age)
常量,变量在使用之前,都不能使用
let age: Int
var height: Int
print(age)
print(height)
下面的代码是错误的(没有指明类型)
let age
age = 20
标识符
标识符(比如常量名,变量名,函数名)几乎可以使用任何字符
标识符不能以数字开头,不能包含空白字符,制表符,箭头灯特殊字符
func ????() {
print("666");
}
????()
let ?? = "ET"
var ?? = "milk"
常见数据类型
值类型:(value type)
1.枚举(enum)Optional
2.结构体(struct)Bool,Int,Float,Double,Character,String, Array,dictionary,Set
引用类型(reference type):类(class)
整数类型:Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64
在32bit平台,Int等价于Int32,如果在64位则Int等价于Int64
整数的最值:UInt8.max,Int16.min
print(Int64.max)
浮点类型:Float,32位,精度只有6位;Double,64位,精度至少15位
let letFloat: Float = 30.0
let letDouble: Double = 30.0
布尔
let bool = true //取反false
字符串
let string = "xaiomage"
字符(可存储ASCII,Unicode字符)
let character: Character = "??"
整数
let intDecimal = 17 //十进制
let intBinary = 0b0001 //二进制
let intOctal = 0o21 //八进制
let intHexadecimal = 0x11 //十六进制
浮点数
let doubleDecimal = 125.0 //十进制,等价于1.25e2(1.25*10^2),0.0125~1.25e-2(1.25*10^(-2))
let doubleHexadecimal1 = 0xfp2 //十六进制,意味着15x2^2,相当于十进制的60.0
let doubleHexadecimal2 = 0xfp-2 //十六进制,意味着15x2^-2,相当于十进制的3.75
以下都是标识12.1875
十进制:12.1875,1.21875e1
十六进制:0xC.3p0
数组
let array = [1, 3, 5, 7, 9];
整数和浮点数都可以添加额外的0或者下划线来增强可读性
100_0000, 1_000_000.000_000_1, 000123.456
字典
let dictionary = ["age":18,"height":168,"weight":120]
类型转换
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 = pi;
自变量可以直接相加,因为数字字面量本身没有明确的类型
let result = 3 + 0.14159
元组(tuple)
let error = (404, "Not Found")
error.0
error.1
let http404Error = (404, "Not Found")
print("The status code is \(http404Error.0)")
let (statusCode, statusMessage) = http404Error
print("The status code is \(statusCode)")
let (justTheStatus, _) = http404Error
print(justTheStatus)
let http200Status = (statusCode: 200, description: "OK")
print("The status code is \(http200Status.statusCode)")
原文地址:https://www.cnblogs.com/coolcold/p/12000567.html