//
// main.swift
// classTest
//
// Created by 小强 on 15/12/8.
// Copyright © 2015年 小强. All rights reserved.
//
// 字典
var airports = ["TYO": "Tokyo", "DUB": "Dublin"];
print(airports);
// 读取和修改字典
print("The dictionary of airport contains \(airports.count) items");
// 使用一个适合类型的 Key 作为下标索引
airports["DUB"] = "London";
print(airports);
if let oldValue = airports.updateValue("Dublin Internation", forKey: "DUB")
{
print("The old value for DUB was \(oldValue).");
}
print(airports);
// 使用下标语法来在字典中检索特定的键对应的值
if let airportName = airports["DUB"]{
print("The name of the airport is \(airportName).");
} else {
print("That airport is not in the airports dictionary");
}
// 通过使用下标语法来通过给某个键的对应值赋值为 nil 来从字典里移除一个键值对
airports["DUB"] = nil;
print(airports);
airports["DUB"] = "Dublin";
print(airports);
// 使用removeValueForKey 方法移除键值对
if let removeValue = airports.removeValueForKey("DUB"){
print("The removed airport's name is \(removeValue).");
} else {
print("The airports dictionary does not contain a value for DUB.");
}
print(airports);
for (airportCode, airportName) in airports{
print("airportCode = \(airportCode): airportName = \(airportName)");
}
for airportCode in airports.keys {
print("Airport code: \(airportCode)");
}
var namesOfIntegers = Dictionary<Int, String>();
namesOfIntegers[16] = "sixteen";
print(namesOfIntegers);
// 使用 for-in 循环来遍历一个集合中的所有元素
for index in 1 ... 5{
print("\(index) times 5 is \(index * 5)");
}
let base = 3;
let power = 10;
var answer = 1;
for _ in 1 ... power{
answer *= base;
}
print("\(base) to the power of \(power) is \(answer).");
// 值绑定
let anotherPoint = (0, 3);
switch anotherPoint {
case (let x, 0):
print("on the x-axis with an x value of \(x).");
case (0, let y):
print("on the y-axis with a y value of \(y).");
case let (x, y):
print("somewhere else at (\(x), \(y)).");
}
// case 块的模式可以使用 where 语句来判断额外的条件
let yetAnotherPoint = (1, -1);
switch yetAnotherPoint {
case let (x, y) where x == y:
print("(\(x),\(y)) is on the line x == y");
case let(x, y) where x == -y:
print("(\(x),\(y)) is on the line x == -y");
case let (x, y):
print("(\(x),\(y)) is just some arbitrary point");
}
let integerToDescripe = 5;
var description = "The number \(integerToDescripe) is "
endSwitch: switch integerToDescripe{
case 2, 3, 5, 7, 11,17, 19:
description += "a prime number, and also";
break endSwitch;
default:
description += " an integer."
}
print(description);