数组 — Array
通过一个默认值重复创建数组
/// 创建一个重复元素为 0.0 且元素个数为 3 的数组
var threeDoubles = Array(repeating: 0.0, count: 3)
/// 创建一个重复元素为 0.1 且元素个数为 3 的数组
var anotherThreeDoubles = Array(repeating: 0.1, count: 3)
创建递增数组
/// 新建一个 0 到 3 的递增数组,每次递增 1
var increasing = Array(0...3)
/// 新建一个 0 到 5 的递增数组,每次递增 1
var increasingByOne = Array(stride(from: 0.0, through: 5.0, by: 1.0))
/// stride(from: through: by: ) 包括 from、through 两个 element
/// stride(from: to: by: ) 包括 from, 但是不包括 to
通过两个数组创建一个新的数组
var sixDoubles = threeDoubles + anotherThreeDoubles
通过字面量创建
var shoppingList: [String] = ["Eggs", "Milk"]
由于 Swift 的数据推断,初始化的时候可以不加数据类型
var shoppingListNew = ["Eggs", "Milk"]
访问和修改数组
shoppingList.count
shoppingList.isEmpty
shoppingList.append("Flour")
shoppingList += ["Baking Powder"]
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
var firstItem = shoppingList[0]
shoppingList[0] = "Six eggs"
shoppingList[4...6] = ["Bananas", "Apples"] // 4.5.6 -> 4.5
shoppingList.insert("Maple Syrup", at: 0)
var returnRemoveString = shoppingList.remove(at: 0)
var returnRemoveLast = shoppingList.removeLast()
遍历
for item in shoppingList {
print(item)
}
同时获取 index 和 item
for (index, item) in shoppingList.enumerated() {
print("Item \(index + 1): \(item)")
}
集合 — Set
存储不同值并且相同类型、不排序
Hash Values for Set Types
- 类型必须是以 Hashable 以存储在集合中,Int 类型
- if a == b,a.hashable == b.hashable
- 使用自定义类型作为集合值类型或者字典key类型,遵循 Hashable
- 遵循 Hashable 协议必须提供 get Int hashValue,该值不需要在相同程序或者不同程序的不同执行中相同
- Hashable 遵循 Equatable,所以还必须提供一个 == 操作符的实现
- == 必须满足三个条件:
(1)a == a 自反性
(2)a == b 等效于 b == a
(3)a == b && b == c 等效于 a == c
创建和实例化空集合
var letters = Set<Character>()
letters.insert("a")
letters = []
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// 不能从一个数组字面量被推断为 Set 数据类型,必须显示声明
// but 不需要写 set 中 的类型
let favoriteGenresNew: Set = ["Rock", "Classical", "Hip hop"]
访问和修改集合
favoriteGenres.count
favoriteGenres.isEmpty
favoriteGenres.insert("Jazz")
if let removedGenre = favoriteGenres.remove("Rock") {
print("\(removedGenre)? I'm over it")
}else {
print("I never much cared for that")
}
if favoriteGenres.contains("Funk") {
print("I get up on the good foot.")
}else {
print("It's too funky in here")
}
遍历集合
for genre in favoriteGenres {
print("\(genre)")
}
for genre in favoriteGenres.sorted() { // < 排序
print("\(genre)")
}
集合操作
var a: Set = Set<String>()
var b: Set = Set<String>()
a.intersection(b) // 交集,共有部分
a.symmetricDifference(b) // 非共有部分总和
a.union(b) // 并集,a + b
a.subtracting(b) // a - a.intersection(b)(交集)
a == b // a 和 b 有所有相同值
a.isSubset(of: b) // a 是不是 b 的子集
a.isSuperset(of: b) // a 是不是 b 的父集
a.isStrictSubset(of: b) // a 是不是 b 的子集,但是不等于 b
a.isStrictSuperset(of: b) // a 是不是 b 的父集,但是不等于 b
a.isDisjoint(with: b) // a 和 b 没有公共部分
字典 — Dictionary
var namesOfIntegers = [Int: String]() // 空数组
namesOfIntegers = [:] // 空数组
var airports: [String: String] = ["YYZ": "Toronto Person", "DUB": "Dublin"] // key: value
访问和修改字典
airports.count
if airports.isEmpty {
print("The airports dictionary is empty")
} else {
print("The airports dictionary is not empty")
}
airports["LHR"] = "London"// 添加一个新值 或 修改值
var returnOldValue = airports.updateValue("London", forKey: "LHR") // 添加一个新值 或 修改值
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("The airport is not in the airports dictionary")
}
移除
airports["APL"] = nil
if let removedValue = airports.removeValue(forKey: "DUB") {
print("The removed airport's name is \(removedValue)")
} else {
print("The airport dictionary does not contain a value for DUB")
}
遍历
for (airportCode, airportName) in airports {
print("\(airportCode) : \(airportName)")
}
// 取出 keys, values
for airportCode in airports.keys.sorted() {
print("Airport code: \(airportCode)")
}
for airportName in airports.values.sorted() {
print("Airport code: \(airportName)")
}
keys,values 初始化数组
let airportName = [String](airports.values)
let airportCode = [String](airports.keys)