The Swift Programming Language-官方教程精译Swift(5)集合类型 -- Collection Types
Swift语言提供经典的数组和字典两种集合类型来存储集合数据。数组用来按顺序存储相同类型的数据。字典虽然无序存储相同类型数据值但是需要由独有的标识符引用和寻址(就是键值对)。
var shoppingList: String[] = ["Eggs", "Milk"]
// shoppingList 已经被构造并且拥有两个初始项。
var shoppingList = ["Eggs", "Milk"]
println("The shopping list contains \(shoppingList.count) items.")
// 打印出"The shopping list contains 2 items."(这个数组有2个项)
if shoppingList.isEmpty {
println("The shopping list is empty.")
} else {
println("The shopping list is not empty.")
}
// 打印 "The shopping list is not empty."(shoppinglist不是空的)
shoppingList.append("Flour")
// shoppingList 现在有3个数据项,有人在摊煎饼
除此之外,使用加法赋值运算符(+=)也可以直接在数组后面添加数据项:
shoppingList += "Baking Powder"
// shoppingList 现在有四项了
我们也可以使用加法赋值运算符(+=)直接添加拥有相同类型数据的数组。
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
// shoppingList 现在有7项了
可以直接使用下标语法来获取数组中的数据项,把我们需要的数据项的索引值放在直接放在数组名称的方括号中:
var firstItem = shoppingList[]
// 第一项是 "Eggs"
shoppingList[] = "Six eggs"
// 其中的第一项现在是 "Six eggs" 而不是 "Eggs"
还可以利用下标来一次改变一系列数据值,即使新数据和原有数据的数量是不一样的。下面的例子把"Chocolate Spread","Cheese",和"Butter"替换为"Bananas"和 "Apples":
shoppingList[...] = ["Bananas", "Apples"]
// shoppingList 现在有六项
注意: 我们不能使用下标语法在数组尾部添加新项。如果我们试着用这种方法对索引越界的数据进行检索或者设置新值的操作,我们会引发一个运行期错误。我们可以使用索引值和数组的count属性进行比较来在使用某个索引之前先检验是否有效。除了当count等于0时(说明这是个空数组),最大索引值一直是count - 1,因为数组都是零起索引。
shoppingList.insert("Maple Syrup", atIndex: )
// shoppingList 现在有7项
// "Maple Syrup" 现在是这个列表中的第一项
这次insert函数调用把值为"Maple Syrup"的新数据项插入shopping列表的最开始位置,并且使用0作为索引值。
let mapleSyrup = shoppingList.removeAtIndex()
//索引值为0的数据项被移除
// shoppingList 现在只有6项,而且不包括Maple Syrup
// mapleSyrup常量的值等于被移除数据项的值 "Maple Syrup"
数据项被移除后数组中的空出项会被自动填补,所以现在索引值为0的数据项的值再次等于"Six eggs":
firstItem = shoppingList[]
// firstItem 现在等于 "Six eggs"
如果我们只想把数组中的最后一项移除,可以使用removeLast方法而不是removeAtIndex方法来避免我们需要获取数组的count属性。就像后者一样,前者也会返回被移除的数据项:
let apples = shoppingList.removeLast()
// 数组的最后一项被移除了
// shoppingList现在只有5项,不包括cheese
// apples 常量的值现在等于"Apples" 字符串
for item in shoppingList {
println(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas
for (index, value) in enumerate(shoppingList) {
println("Item \(index + 1): \(value)")
}
// Item 1: Six eggs
// Item 2: Milk
// Item 3: Flour
// Item 4: Baking Powder
// Item 5: Bananas
var someInts = Int[]()
println("someInts is of type Int[] with \(someInts。count) items。")
// 打印 "someInts is of type Int[] with 0 items。"(someInts是0数据项的Int[]数组)
someInts.append()
// someInts 现在包含一个INT值
someInts = []
// someInts 现在是空数组,但是仍然是Int[]类型的。
var threeDoubles = Double[](count: , repeatedValue:0.0)
// threeDoubles 是一种 Double[]数组, 等于 [0.0, 0.0, 0.0]
var anotherThreeDoubles = Array(count: , repeatedValue: 2.5)
// anotherThreeDoubles is inferred as Double[], and equals [2.5, 2.5, 2.5]
var sixDoubles = threeDoubles + anotherThreeDoubles
// sixDoubles 被推断为 Double[], 等于 [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
[key : value , key : value , key : value ]
var airports: Dictionary<String, String> = ["TYO": "Tokyo", "DUB": "Dublin"]
var airports = ["TYO": "Tokyo", "DUB": "Dublin"]
println("The dictionary of airports contains \(airports.count) items.")
// 打印 "The dictionary of airports contains 2 items."(这个字典有两个数据项)
我们也可以在字典中使用下标语法来添加新的数据项。可以使用一个合适类型的key作为下标索引,并且分配新的合适类型的值:
airports["LHR"] = "London"
// airports 字典现在有三个数据项
我们也可以使用下标语法来改变特定键对应的值:
airports["LHR"] = "London Heathrow"
// "LHR"对应的值 被改为 "London Heathrow
作为另一种下标方法,字典的updateValue(forKey:)方法可以设置或者更新特定键对应的值。就像上面所示的示例,updateValue(forKey:)方法在这个键不存在对应值的时候设置值或者在存在时更新已存在的值。和上面的下标方法不一样,这个方法返回更新值之前的原值。这样方便我们检查更新是否成功。
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现在被移除了
另外,removeValueForKey方法也可以用来在字典中移除键值对。这个方法在键值对存在的情况下会移除该键值对并且返回被移除的value或者在没有值的情况下返回nil:
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."(被移除的机场名字是都柏林国际)
for (airportCode, airportName) in airports {
prINTln("\(airportCode): \(airportName)")
}
// TYO: Tokyo
// LHR: London Heathrow
for airportCode in airports.keys {
prINTln("Airport code: \(airportCode)")
}
// Airport code: TYO
// Airport code: LHR for airportName in airports.values {
prINTln("Airport name: \(airportName)")
}
// Airport name: Tokyo
// Airport name: London Heathrow
let airportCodes = Array(airports.keys)
// airportCodes is ["TYO", "LHR"] let airportNames = Array(airports.values)
// airportNames is ["Tokyo", "London Heathrow"]
注意: Swift 的字典类型是无序集合类型。其中字典键,值,键值对在遍历的时候会重新排列,而且其中顺序是不固定的。
var namesOfIntegers = Dictionary<Int, String>()
// namesOfIntegers 是一个空的 Dictionary<Int, String>
namesOfIntegers[] = "sixteen"
// namesOfIntegers 现在包含一个键值对
namesOfIntegers = [:]
// namesOfIntegers 又成为了一个 Int, String类型的空字典
注意: 在后台,Swift 的数组和字典都是由泛型集合来实现的,想了解更多泛型和集合信息请参见泛型。
The Swift Programming Language-官方教程精译Swift(5)集合类型 -- Collection Types的更多相关文章
- The Swift Programming Language-官方教程精译Swift(6)控制流--Control Flow
Swift提供了类似C语言的流程控制结构,包括可以多次执行任务的for和while循环,基于特定条件选择执行不同代码分支的if和switch语句,还有控制流程跳转到其他代码的break和continu ...
- The Swift Programming Language-官方教程精译Swift(2)基础知识
Swift 的类型是在 C 和 Objective-C 的基础上提出的,Int是整型:Double和Float是浮点型:Bool是布尔型:String是字符串.Swift 还有两个有用的集合类型,Ar ...
- The Swift Programming Language-官方教程精译Swift(1)小试牛刀
通常来说,编程语言教程中的第一个程序应该在屏幕上打印“Hello, world”.在 Swift 中,可以用一行代码实现: println("hello, world") 如果你 ...
- The Swift Programming Language-官方教程精译Swift(9) 枚举-- --Enumerations
枚举定义了一个通用类型的一组相关的值,使你可以在你的代码中以一个安全的方式来使用这些值. 如果你熟悉 C 语言,你就会知道,在 C 语言中枚举指定相关名称为一组整型值.Swift 中的枚举更加灵活 ...
- The Swift Programming Language-官方教程精译Swift(8)闭包 -- Closures
闭包是功能性自包含模块,可以在代码中被传递和使用. Swift 中的闭包与 C 和 Objective-C中的 blocks 以及其他一些编程语言中的 lambdas 比较相似. 闭包可以捕获和存储其 ...
- The Swift Programming Language-官方教程精译Swift(7)函数 -- Functions
函数 函数是执行特定任务的代码自包含块.通过给定一个函数名称标识它是什么,并在需要的时候使用该名称来调用函数以执行任务. Swift的统一的功能语法足够灵活的,可表达任何东西,无论是不带参数名称的简单 ...
- The Swift Programming Language-官方教程精译Swift(4)字符串和字符
String 是一个有序的字符集合,例如 "hello, world", "albatross".Swift 字符串通过 String 类型来表示,也可以表示为 ...
- The Swift Programming Language-官方教程精译Swift(3)基本运算符
运算符是检查, 改变, 合并值的特殊符号或短语. 例如, 加号 + 把计算两个数的和(如 let i = 1 + 2). 复杂些的运行算包括逻辑与&&(如 if enteredDoor ...
- iOS Swift-简单值(The Swift Programming Language)
iOS Swift-简单值(The Swift Programming Language) 常量的声明:let 在不指定类型的情况下声明的类型和所初始化的类型相同. //没有指定类型,但是初始化的值为 ...
随机推荐
- httpclient 文件上传
/** * 上传文件 */ public static Boolean uploadFile(String fileName, String url) { ...
- Linking pronunciation in English
1.constant+vowel stand up give up get up 2.vowel+vowel 2.1 i:/i/ei/ai/oi [j] stay up carry it 2.2 u: ...
- Linux删除以破折号开头的文件Windows在批处理文件来删除隐藏属性
昨天去打印店打印的材料.结果中毒.所有的文件被隐藏.生成一个一堆快捷键.回来后.我很容易地把它放入Linux机,我想删除这些文件怪. 下面是该过程,遇到的问题. 1.您无法删除'-'该文件的开头 最初 ...
- web 环境项目(intellj部署的tomcat) 重启时报 Exception in thread "HouseKeeper" java.lang.NullPointerException (转)
Exception in thread "HouseKeeper" java.lang.NullPointerException at org.logicalcobwebs.pro ...
- Event Sourcing
Event Sourcing - ENode(二) 接上篇文章继续 http://www.cnblogs.com/dopeter/p/4899721.html 分布式系统 前篇谈到了我们为何要使用分布 ...
- java通过抛异常来返回提示信息
结论:如果把通过抛异常的方式得到提示信息,可以使用java.lang.Throwable中的构造函数: public Throwable(String message) { fillInStackTr ...
- HTTP简单的解析协议
1.HTTP定义的协议 官方的定义: WWW这是Internet作为传输介质的应用.WWW主变速器单元是在线Web网页.WWW它正在给客户/server计算模型,由Web浏览器Webse ...
- 如何安装一个优秀的BUG管理平台(转)
前言 就BUG管理而言,国内的禅道做得很不错,而且持续有更新.我们来看看如何从头到尾安装禅道,各位要注意的是,不是文章深或者浅,而是文章如何在遇到问题的时候,从什么途径和用什么方法解决问题的.现在发觉 ...
- Oracle 多表关联更新
drop table course; create table course ( id integer, teacherNo integer, teacherDesc ), teacherName ) ...
- SharePoint 如何使自己的网页自动跳转
SharePoint 如何使自己的网页自动跳转 SharePoint自动制作自己的网页跳的很easy,只有在页面上要添加一个Web部分--内容编辑器,对应的js代码就可以. ...