一.常量和变量
1.声明
let maximumNumberOfLoginAttempts = 10 //常量
var currentLoginAttempt = 0 //变量
2.声明格式
var x = 0.0, y = 0.0 z = 0.0 //可在一行中声明多个常量或者多个变量,用逗号隔开
3.类型标注:变量名后面加上冒号和空格,再加上类型名称
4.输出:println
println("The current value of friendWelcome is \(friendWelcom)")
5.注意点⚠️:
(1)当表达式中同时出现整数和浮点数的时候,系统会推测为Double类型
let anotherPi = 3 + 0.14159
6.断言 assert :断言信息不能使用字符串插值,断言信息可以省略
let age = -3;
assert(age>=0, "A person is age cannot be less than zero")
二.元组
1.创建元组
let http404Error = (404,"Not Found")
let (statuCode, statusMessage) = http404Error
print("The status code is \(statuCode)")
print("The status message is \(statusMessage)")
let (justTheStatusCode, _) = http404Error;
print("The status code is \(justTheStatusCode)")
5.通过下标来访问元组中的元素,下标从零开始
print("he status code is \(http404Error.0)")
print("The status message is \(http404Error.1)")
let http200Status = (statusCode:200, description:"OK")
print(http200Status.statusCode);
print(http200Status.description)
——用于函数返回值
——如果较为复杂的数据结构,建议使用结构体或者类
三.可选 optionais:来处理值可能缺失的情况
1.可选?,强制解析!
let possibleNumber = "123"
let convertedNumber = Int(possibleNumber)
代码解析: convertedNumber被推测为类型 "Int?",或者类型 "optional Int"
Int(possibleNumber)方法可能会失败,所以它返回一个可选的(Optional)Int,而不是一个Int。
一个可选的Int被写作 “Int?”,而不是Int,问好表示包含的值是可选,也就是说可能包含Int值也可能不包含
if (convertedNumber != nil) {
print("\(possibleNumber) has an integer value of \(convertedNumber!)")
}else {
print("\(possibleNumber) could not be converted to an integer")
}
代码解析:当确定可选包含值之后,可以在可选的名字后面加一个感叹号“!”来获取值——称为可选值的强制解析
注意:使用!来获取一个不存在的可选值会导致运行时错误,使用!来强制解析之前,一定要确定可选包含一个非nil的值
2.可选绑定(optional binding):判断可选是否包含值,如果包含就把值赋给一个临时常量或变量
if let actualNumber = Int(possibleNumber) {
print("\(possibleNumber) has an integer value of \(actualNumber)")
}else {
print("\(possibleNumber) could not be converted to an integer")
}
代码解析:如果Int(possibleNumber)返回的可选Int包含一个值,创建一个叫做actualNumber的新常量并将可选包含的值赋给它
如果转换成功,actualNumber常量可以在if语句的第一个分支中使用,它已经被可选包含的值初始化,所以不需要再使用!后缀来获取它 的值
3.nil:可以给可选变量赋值为nil来表示它没有值
var serverResponseCode: Int? = 404 //serverResponseCode 包含一个可选的Int值 404
serverResponseCode = nil //serverResponseCode 现在不包含值了
注意⚠️:nil不能用于非可选的常量和变量,如果代码中有常量或者变量需要处理值缺失的情况,请把它们声明成对应的可选类型
var surveAnswer: String? //未赋值,值自动设置为nil
OC中的nil和Swift的nil区别:
OC中nil是指空指针
Swift中nil是一个确定的值,任何类型的可选都可以被设置为nil,不只是对象类型
4.隐式解析可选:
——第一次被赋值后,可以确定一个可选总会有值,每次都要判断和解析可选值是非常抵消的,因为可以确定它总会有值。
——隐式解析可选,把想要用做可选的类型的后面的问好改成感叹号来声明一个隐式解析可选
——当可选被第一次赋值之后就可以确定之后一直有值的时候,隐式解析可选非常有用。主要被用做swift中类的构造过程中,参考类实例之间的循环强引用
let possibleString: String? = "An optional atring"
print(possibleString!)
let assumedString: String! = "An implicitly unwrapped optional string"
print(assumedString)
注意⚠️:如果一个变量之后可能变成nil的话,不要使用隐式解析可选
四.类型别名:typealias
typealias AudioSample = UInt16