首页 > 代码库 > Swift-4-数组和字典
Swift-4-数组和字典
// Playground - noun: a place where people can playimport 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 optionallet oldValue = http://www.mamicode.com/airports.updateValue("Dublin Airport", forKey: "DUB")// 移除键值对airports["DUB"] = nilairports.removeValueForKey("DUB")// 遍历for (key, value) in airports { println("key: \(key), value: \(value)")}
Swift-4-数组和字典
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。