数组(Swift 的 Array类型被桥接到了基础框架的 NSArray类上。)
数组创建
// Swift 数组的类型完整写法是 Array<Element>
// 同样可以简写数组的类型为 [Element]。
// 更推荐简写并且全书涉及到数组类型的时候都会使用简写。
// 创建一个空数组
var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.")
someInts.append(3)
// someInts now contains 1 value of type Int
someInts = []
// someInts is now an empty array, but is still of type [Int]
//使用默认值创建数组
var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]
//通过连接两个数组来创建数组
var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
// anotherThreeDoubles is of type [Double], and equals [2.5, 2.5, 2.5]
var sixDoubles = threeDoubles + anotherThreeDoubles
// sixDoubles is inferred as [Double], and equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
//使用数组字面量创建数组
var shoppingList: [String] = ["Eggs", "Milk"]
// shoppingList has been initialized with two initial items
//依托于 Swift 的类型推断,如果你用包含相同类型值的数组字面量初始化数组,就不需要写明数组的类型。 shoppingList的初始化可以写得更短
var shoppingList = ["Eggs", "Milk"]
// 避免推断
var shoppingList = ["Eggs", "Milk"] as [Any]
数组操作
//.isEmpty属性来作为检查 count属性是否等于 0的快捷方式
if shoppingList.isEmpty {
print("The shopping list is empty.")
} else {
print("The shopping list is not empty.")
}
// prints "The shopping list is not empty."
//添加元素
shoppingList.append("Flour")
shoppingList[0] = "Six eggs"
shoppingList[4...6] = ["Bananas", "Apples"]
//插入
shoppingList.insert("Maple Syrup", at: 0)
//删除
let mapleSyrup = shoppingList.remove(at: 0)
//另外,可以使用加赋值运算符 ( +=)来在数组末尾添加一个或者多个同类型元素:
shoppingList += ["Baking Powder"]
// shoppingList now contains 4 items
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
// shoppingList now contains 7 items
//取值
var firstItem = shoppingList[0]
数组遍历
//你可以用 for-in循环来遍历整个数组中值的合集:
for item in shoppingList {
print(item)
}
//你需要每个元素以及值的整数索引,使用 enumerated()方法来遍历数组。 enumerated()方法返回数组中每一个元素的元组,包含了这个元素的索引和值。你可以分解元组为临时的常量或者变量作为遍历的一部分:
for (index, value) in shoppingList.enumerated() {
print("Item \(index + 1): \(value)")
}
合集(Swift 的 Set类型桥接到了基础框架的 NSSet类上。)
合集创建(合集类型不能从数组字面量推断出来,所以 Set类型必须被显式地声明)
//你可以使用初始化器语法来创建一个确定类型的空合集:
var letters = Set<Character>()
print("letters is of type Set<Character> with \(letters.count) items.")
letters.insert("a")
// letters now contains 1 value of type Character
letters = []
// letters is now an empty set, but is still of type Set<Character>
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres has been initialized with three initial items
合集操作
//合集当中元素的数量,检查它的只读 count
print("I have \(favoriteGenres.count) favorite music genres.")
// isEmpty属性作为检查 count属性是否等于 0
if favoriteGenres.isEmpty {
print("As far as music goes, I'm not picky.")
} else {
print("I have particular music preferences.")
}
// prints "I have particular music preferences."
//插入
favoriteGenres.insert("Jazz")
// favoriteGenres now contains 4 items
//删除
if let removedGenre = favoriteGenres.remove("Rock") {
print("\(removedGenre)? I'm over it.")
} else {
print("I never much cared for that.")
}
// prints "Rock? I'm over it."
//包含
if favoriteGenres.contains("Funk") {
print("I get up on the good foot.")
} else {
print("It's too funky in here.")
}
合集遍历
//你可以在 for-in循环里遍历合集的值。
for genre in favoriteGenres {
print("\(genre)")
}
// Classical
// Jazz
// Hip hop
//Set类型是无序的。要以特定的顺序遍历合集的值,使用 sorted()方法
for genre in favoriteGenres.sorted() {
print("\(genre)")
}
合集操作
/**
使用 A.intersection(B:) : A∩B
使用 A.symmetricDifference(B:):A∪B - A∩B
使用 A.union(B:) : A∪B
使用 A.subtracting(B:) : A-B
*/
let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]
oddDigits.union(evenDigits).sorted()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
oddDigits.intersection(evenDigits).sorted()
// []
oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
// [1, 9]
oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()
// [1, 2, 9]
字典(Dictionary桥接到了基础框架的 NSDictionary类。)
字典创建
//Swift 的字典类型写全了是这样的: Dictionary<Key, Value>,
//其中的 Key是用来作为字典键的值类型, Value就是字典为这些键储存的值的类型。
//简写的形式来写字典的类型为 [Key: Value]。尽管两种写法是完全相同的,但本书所有提及字典的地方都会使用简写形式。
var namesOfIntegers = [Int: String]()
// namesOfIntegers is an empty [Int: String] dictionary
namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type [Int: String]
//用字典字面量创建字典
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
//与数组一样,如果你用一致类型的字典字面量初始化字典,就不需要写出字典的类型了。 airports的初始化就能写的更短:
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
//避免类型推断
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin",2:"zzzz"] as [AnyHashable : String]
字典操作
//使用 count只读属性来找出 Dictionary拥有多少元素
print("The airports dictionary contains \(airports.count) items.")
//isEmpty属性作为检查 count属性是否等于 0
if airports.isEmpty {
print("The airports dictionary is empty.")
} else {
print("The airports dictionary is not empty.")
}
// 赋值
airports["LHR"] = "London"
//更改
airports["LHR"] = "London Heathrow"
//updateValue(_:forKey:)方法来设置或者更新特点键的值
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
print("The old value for DUB was \(oldValue).")
}
if let airportName = airports["DUB"] {
print("The name of the airport is \(airportName).")
} else {
print("That airport is not in the airports dictionary.")
}
//删除
airports["APL"] = nil
//airports.removeValue 删除
if let removedValue = airports.removeValue(forKey: "DUB") {
print("The removed airport's name is \(removedValue).")
} else {
print("The airports dictionary does not contain a value for DUB.")
}
字典遍历
//for-in循环来遍历字典的键值对
for (airportCode, airportName) in airports {
print("\(airportCode): \(airportName)")
}
//你同样可以通过访问字典的 keys和 values属性来取回可遍历的字典的键或值的集合:
for airportCode in airports.keys {
print("Airport code: \(airportCode)")
}
// Airport code: YYZ
// Airport code: LHR
for airportName in airports.values {
print("Airport name: \(airportName)")
}
// Airport name: Toronto Pearson
// Airport name: London Heathrow
//需要和接收 Array实例的 API 一起使用字典的键或值,就用 keys或 values属性来初始化一个新数组
let airportCodes = [String](airports.keys)
// airportCodes is ["YYZ", "LHR"]
let airportNames = [String](airports.values)
// airportNames is ["Toronto Pearson", "London Heathrow"]