Swift 练习题 2 答案: 数组,字典和Set
小牛哥上星期参加 Big Nerd Ranch 的 Swift 培训,期间做了很多练习,
在这里翻译一下跟大家分享。
更多内容请大家关注我的微博:http://www.weibo.com/u/2822867275
这是第2 部分,第一部分是关于 Optional 的,也在我的微博里。
请大家新建一个 Playground 文件,把下面的内容粘贴就去。
// Collections Exercises
// ------------------------------------------------------
// * 什么是不变量 (immutable) :一旦初始化后不能修改里面的内容。
//
// ------------------------------------------------------
// Arrays
// ----------------------------------------
/* 练习 #1
* 1) 定义一个不变量数组,以 numbers 为名
* 2) numbers 含有这些词 "Zero", "One", "Two", "Three", 和 "Four"
*/
// 练习1 答案:
let numbers = ["Zero","One","Two","Three","Four"]
// ----------------------------------------
/* 练习 #2
* 1) 定义一个可修改的数组 mutableNumbers, 初始值为 练习 1 的答案
*/
// 练习 2 答案:
var mutableNumbers = numbers
// ----------------------------------------
/* 练习 #3
* 1) 添加 "Five" 到 mutableNumbers 里
*/
// 练习 3 答案:
mutableNumbers.append("Five")
// Dictionaries
// ----------------------------------------
/* 练习 #4
* 1) 定义一个可变得的字典, 变量名为 numberDictionary ,类型为 [String: Int]
* 2) 使用循环语句,让字典的 key 为 numbers 的各项,值为相应的整数, 如: ["One": 1, "Two": 2,...]
* 3)把字典的各项打印出来
*/
// 练习4 答案:
var numberDictionary = [String:Int]()
for var i = 0; i < numbers.count; i++ {
numberDictionary[numbers[i]] = i
}
print(numberDictionary)
/* 练习 #5
* 1) 定义一个不变量,名字为four, 初始值为 numberDictionary key 为 "Four" 的值
* 2) 注意 four 的类型
* 3) 为什么 four 会有这样的类型
*/
// 练习 5 答案:
let four = numberDictionary["Four"]
// four 的类型为 Int?, 因为字典的值为Optional.
// ----------------------------------------
// Sets
/* 练习 #6
* 1) 由数组 ["Pear", "Apple", "Orange", "Banana"] 来初始化一个不变量 Set,名字为 fruits,
* 2) 由数组 ["Broccoli", "Lettuce", "Zuccini", "Onion"] 来初始化一个不变量 Set,名字为 vegetables
* 3) 判断这两个 Set 是否不相交, 结果保存在变量 disjointSets 里
* 4) 定义一个新的变量 Set,名字为healthy, 初始值为前两个Set的合集
* 5) 添加 "Peach" 到 healthy 里
*/
// 练习6 答案:
let fruits: Set = ["Pear", "Apple", "Orange", "Banana"]
let vegetables: Set = ["Broccoli", "Lettuce", "Zuccini", "Onion"]
let disjointSets = fruits.isDisjointWith(vegetables)
print("fruits and vegetables are disjoint: \(disjointSets)")
var healthy = fruits.union(vegetables)
healthy.insert("Peach")
/* 练习 #7
* 1) 基于练习 6, 检验 fruits 和 vegetables 是否为 healthy 的子集
* 2) 定义一个不变量 Set, 名字为 freshToday, 内容为 ["Beef", "Pear", "Lettuce", "Sausage"]
* 3) 查找一下 freshToday 里哪项属于 healthy
*/
//练习7 答案:
let fruitsInHealthy = fruits.isSubsetOf(healthy)
print("Are fruits healthy? \(fruitsInHealthy)")
let vegetablesInHealthy = vegetables.isSubsetOf(healthy)
print("Are vegetables healthy? \(vegetablesInHealthy)")
let freshToday: Set = ["Beef", "Pear", "Lettuce", "Sausage"]
let healthyAndFresh = freshToday.intersect(healthy)
for item in healthyAndFresh {
print("Healthy and fresh: \(item)")
}
// ----------------------------------------
/* 练习 #8:
* 1) 使用 数组的 enumerate() 方法来重做练习 4 的赋值过程
*/
//练习8 答案:
var anotherNumberDictionary = [String:Int]()
for (index, value) in numbers.enumerate() {
anotherNumberDictionary[value] = index
}
print(anotherNumberDictionary)