//swift
// main.swiftspa
// classTest3d
//code
// Created by 小強 on 15/12/8.orm
// Copyright © 2015年 小強. All rights reserved.索引
//ip
// 字典rem
var airports = ["TYO": "Tokyo", "DUB": "Dublin"];it
print(airports);io
// 讀取和修改字典
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);