// Playground - noun: a place where people can play import UIKit // 数组 字典 // 集合的可变性 赋值给var的集合是可变的mutable,赋值给let的集合是不可变的immutable // 数组 Array<SomeType> 等价于 [SomeType] var shoppingList : [String] = ["Eggs", "Milk"] // var shoppingList = ["Eggs", "Milk"] 自动推断类型 // 数组计数 println("the shopping list contains \(shoppingList.count) items") // 检查数组是否为空 if shoppingList.isEmpty { println("the shopping list is empty") } else { println("the shopping list is not empty") } // 向数组中添加元素 shoppingList.append("Flour") shoppingList += ["Baking Powder"] // 访问数组中元素 var firstItem = shoppingList[0] // 批量替换数组中元素 用于替换的数组元素个数与替换的范围不一定要相同 shoppingList[1...2] = ["Apples"] // 插入元素 shoppingList.insert("Maple Syrup", atIndex: 0) // 从数组中移除元素 let mapleSyrup = shoppingList.removeAtIndex(0) shoppingList.removeRange(Range(start: 1, end: 2)) shoppingList.removeLast() // 遍历数组 for item in shoppingList { println(item) } for (index, item) in enumerate(shoppingList) { println("Item \(index + 1): \(item)") } // 创建并初始化数组 var someInts = [Int]() println("someInts is of type [Int] with \(someInts.count) items") // 创建数组时赋默认值 var thressDoubles = [Double](count: 5, repeatedValue: 0.0) // 组合数组 var anotherDoubles = [Double](count: 3, repeatedValue: 0.1) var eightDouble = thressDoubles + anotherDoubles // 字典 //Dictionary<key, value> [key : value] var airports: [String : String] = ["YYZ" : "Toronto Pearson", "DUB" : "Dublin"] // var airports = ["YYZ" : "Toronto Pearson", "DUB" : "Dublin"] // 访问、修改字典 println("The airports dictionary contains \(airports.count) items") if airports.isEmpty { println("The airports dictionary is empty") } else { println("The airports dictionary is not empty") } // 添加元素 airports["LHR"] = "London" airports["LHR"] = "London Heathrow" // 通过方法设置键值. 返回被替换的value optional let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") // 移除键值对 airports["DUB"] = nil airports.removeValueForKey("DUB") // 遍历 for (key, value) in airports { println("key: \(key), value: \(value)") }