常量和變量
常量和变量把一个名字(比如maximumNumberOfLoginAttempts或者welcomeMessage)和一个指定类型的值(比如数字10或者字符串"Hello")关联起来。常量的值一旦设定就不能改变,而变量的值可以随意更改。
声明常量和变量
常量和变量必须在使用前声明,用let来声明常量,用var来声明变量。下面的例子展示了如何用常量和变量来记录用户尝试登录的次数:
- let maximumNumberOfLoginAttempts = 10
- var currentLoginAttempt = 0
类型标注
当你声明常量或者变量的时候可以加上类型标注(type annotation),说明常量或者变量中要存储的值的类型。如果要添加类型标注,需要在常量或者变量名后面加上一个冒号和空格,然后加上类型名称。
这个例子给welcomeMessage变量添加了类型标注,表示这个变量可以存储String类型的值:
- var welcomeMessage: String
声明中的冒号代表着“是...类型”,所以这行代码可以被理解为:
“声明一个类型为String,名字为welcomeMessage的变量。”
“类型为String”的意思是“可以存储任意String类型的值。”
welcomeMessage变量现在可以被设置成任意字符串:
- welcomeMessage = "Hello"
元組
元组(tuples)把多个值组合成一个复合值。元组内的值可以使任意类型,并不要求是相同类型。
下面这个例子中,(404, "Not Found")是一个描述 HTTP 状态码(HTTP status code)的元组。HTTP 状态码是当你请求网页的时候 web 服务器返回的一个特殊值。如果你请求的网页不存在就会返回一个404 Not Found状态码。
- let http404Error = (404, "Not Found")
- // http404Error 的类型是 (Int, String),值是 (404, "Not Found")
(404, "Not Found")元组把一个Int值和一个String值组合起来表示 HTTP 状态码的两个部分:一个数字和一个人类可读的描述。这个元组可以被描述为“一个类型为(Int, String)的元组”。
你可以把任意顺序的类型组合成一个元组,这个元组可以包含所有类型。只要你想,你可以创建一个类型为(Int, Int, Int)或者(String, Bool)或者其他任何你想要的组合的元组。
你可以将一个元组的内容分解(decompose)成单独的常量和变量,然后你就可以正常使用它们了:
- let (statusCode, statusMessage) = http404Error
- println("The status code is (statusCode)")
- // 输出 "The status code is 404"
- println("The status message is (statusMessage)")
- // 输出 "The status message is Not Found"
- let someString = "Some string literal value"
- var variableString = "Horse"
- variableString += " and carriage"
- // variableString 现在为 "Horse and carriage"
- let constantString = "Highlander"
- constantString += " and another Highlander"
- // 这会报告一个编译错误(compile-time error) - 常量不可以被修改。
注意:在 Objective-C 和 Cocoa 中,您通过选择两个不同的类( NSString 和 NSMutableString )来指定该字符串是否可以被修改,Swift中的字符串是否可以修改仅通过定义的是变量还是常量来决定,实现了多种类型可变性操作的统一。 |
- var shoppingList: String[] = ["Eggs", "Milk"]
- // shoppingList 已经被构造并且拥有两个初始项。
- println("The shopping list contains (shoppingList.count) items.")
- // 打印出"The shopping list contains 2 items."(这个数组有2个项)
- shoppingList.append("Flour")
- // shoppingList 现在有3个数据项,有人在摊煎饼
- shoppingList.insert("Maple Syrup", atIndex: 0)
- // shoppingList 现在有7项
- // "Maple Syrup" 现在是这个列表中的第一项
- [key 1: value 1, key 2: value 2, key 3: value 3]
- var airports: Dictionary<String, String> = ["TYO": "Tokyo", "DUB": "Dublin"]
- println("The dictionary of airports contains (airports.count) items.")
- // 打印 "The dictionary of airports contains 2 items."(这个字典有两个数据项)
- airports["LHR"] = "London"
- // airports 字典现在有三个数据项
- airports["LHR"] = "London Heathrow"
- // "LHR"对应的值 被改为 "London Heathrow
- if let oldValue = airports.updateValue("Dublin Internation", forKey: "DUB") {
- println("The old value for DUB was (oldValue).")
- }
- // 打印出 "The old value for DUB was Dublin."(dub原值是dublin)
- if let airportName = airports["DUB"] {
- println("The name of the airport is (airportName).")
- } else {
- println("That airport is not in the airports dictionary.")
- }
- // 打印 "The name of the airport is Dublin INTernation."(机场的名字是都柏林国际)
- airports["APL"] = "Apple Internation"
- // "Apple Internation"不是真的 APL机场, 删除它
- airports["APL"] = nil
- // APL现在被移除了
- if let removedValue = airports.removeValueForKey("DUB") {
- println("The removed airport's name is (removedValue).")
- } else {
- println("The airports dictionary does not contain a value for DUB.")
- }
- // 打印 "The removed airport's name is Dublin International."(被移除的机场名字是都柏林国际)