Swift:集合类型

2018-07-08  本文已影响5人  伯wen
Swift 语言提供 Arrays、Sets 和 Dictionaries 三种基本的集合类型用来存储集合数据。
数组(Arrays)是有序数据的集。
集合(Sets)是无序无重复数据的集。
字典(Dictionaries)是无序的键值对的集。

Swift 语言中的 Arrays、Sets 和 Dictionaries 中存储的数据值类型必须明确。
这意味着我们不能把错误的数据类型插入其中。
同时这也说明你完全可以对取回值的类型非常放心。

一、集合的可变性

二、数组

1、创建一个空数组
let arr0 = [Int]()
let arr1: [Int] = []
let arr2 = [] as [Int]
let arr3 = Array<Int>()
arr.append(3)
// arr 现在包含一个 Int 值
arr = []
// arr 现在是空数组,但是仍然是 [Int] 类型的。
2、创建一个带有默认值的数组
var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles 是一种 [Double] 数组,等价于 [0.0, 0.0, 0.0]
3、通过两个数组相加创建一个数组
var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
// anotherThreeDoubles 被推断为 [Double],等价于 [2.5, 2.5, 2.5]

var sixDoubles = threeDoubles + anotherThreeDoubles
// sixDoubles 被推断为 [Double],等价于 [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
4、用数组字面量构造数组
// [value 1, value 2, value 3]

var shoppingList: [String] = ["Eggs", "Milk"]
// shoppingList 已经被构造并且拥有两个初始项。
var shoppingList = ["Eggs", "Milk"]
5、访问和修改数组
print("The shopping list contains \(shoppingList.count) items.")
// 输出 "The shopping list contains 2 items."(这个数组有2个项)
if shoppingList.isEmpty {
    print("The shopping list is empty.")
} else {
    print("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 现在有七项了
var firstItem = shoppingList[0]
// 第一项是 "Eggs"
shoppingList[0] = "Six eggs"
// 其中的第一项现在是 "Six eggs" 而不是 "Eggs"
shoppingList[4...6] = ["Bananas", "Apples"]
// shoppingList 现在有6项

注意
不可以用下标访问的形式去在数组尾部添加新项。

var a = [Int]()
for i in 0..<10 {
    a[i] = i      // 报错" Thread 1: Fatal error: Index out of range
}
print(a)
shoppingList.insert("Maple Syrup", at: 0)
// shoppingList 现在有7项
// "Maple Syrup" 现在是这个列表中的第一项
var a = [Int]()
for i in 0..<10 {
    a.insert(i, at: i)
}
print(a)      // 打印: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let mapleSyrup = shoppingList.remove(at: 0)
// 索引值为0的数据项被移除
// shoppingList 现在只有6项,而且不包括 Maple Syrup
// mapleSyrup 常量的值等于被移除数据项的值 "Maple Syrup"
firstItem = shoppingList[0]
// firstItem 现在等于 "Six eggs"
let apples = shoppingList.removeLast()
// 数组的最后一项被移除了
// shoppingList 现在只有5项,不包括 Apples
// apples 常量的值现在等于 "Apples" 字符串
6、数组的遍历
for item in shoppingList {
    print(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas
for (index, value) in shoppingList. enumerated() {
    print("Item \(String(index + 1)): \(value)")
}
// Item 1: Six eggs
// Item 2: Milk
// Item 3: Flour
// Item 4: Baking Powder
// Item 5: Bananas

三、集合

1、集合类型的哈希值

注意
你可以使用你自定义的类型作为集合的值的类型或者是字典的键的类型,但你需要使你的自定义类型符合 Swift 标准库中的 Hashable 协议。

2、集合类型语法
3、创建和构造一个空的集合
var letters = Set<Character>()
print("letters is of type Set<Character> with \(letters.count) items.")
// 打印 "letters is of type Set<Character> with 0 items."
letters.insert("a")
// letters 现在含有1个 Character 类型的值
letters = []
// letters 现在是一个空的 Set, 但是它依然是 Set<Character> 类型
4、用数组字面量创建集合
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres 被构造成含有三个初始值的集合
var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]
5、访问和修改一个集合
print("I have \(favoriteGenres.count) favorite music genres.")
// 打印 "I have 3 favorite music genres."
if favoriteGenres.isEmpty {
    print("As far as music goes, I'm not picky.")
} else {
    print("I have particular music preferences.")
}
// 打印 "I have particular music preferences."
favoriteGenres.insert("Jazz")
// favoriteGenres 现在包含4个元素
if let removedGenre = favoriteGenres.remove("Rock") {
    print("\(removedGenre)? I'm over it.")
} else {
    print("I never much cared for that.")
}
// 打印 "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.")
}
// 打印 "It's too funky in here."
6、遍历一个集合
for genre in favoriteGenres {
    print("\(genre)")
}
// Classical
// Jazz
// Hip hop
for genre in favoriteGenres.sorted() {
    print("\(genre)")
}
// prints "Classical"
// prints "Hip hop"
// prints "Jazz

四、集合操作

1、基本集合操作
let a: Set = [1, 3, 5, 7, 9]
let b: Set = [0, 2, 4, 6, 8]
let c: Set = [2, 3, 5, 7]

// 交集   同时即在a中, 也在c中
result = a.intersection(c).sorted()
print(result)        // 打印: [3, 5, 7]
// 并集   a中和b中
var result = a.union(b).sorted()
print(result)        // 打印: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
// 对称差集   在a中或在c中, 但不同时在a和c中
result = a.symmetricDifference(c).sorted()
print(result)        // 打印: [1, 2, 9]
// 差集  在a中而不在c中
result = a.subtracting(c).sorted()
print(result)        // 打印: [1, 9]
2、集合成员关系和相等
let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
let cityAnimals: Set = ["🐦", "🐭"]

houseAnimals.isSubset(of: farmAnimals)
// true
farmAnimals.isSuperset(of: houseAnimals)
// true
farmAnimals.isDisjoint(with: cityAnimals)
// true

五、字典

1、字典类型简化语法
2、创建一个空字典
let dict1 = Dictionary<Int, String>()
let dict2 = [Int:String]()
let dict3: [Int:String] = [:]
let dict4 = [:] as [Int:String]
3、用字典字面量创建字典
[key 1: value 1, key 2: value 2, key 3: value 3]
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
4、访问和修改字典
print("The dictionary of airports contains \(airports.count) items.")
// 打印 "The dictionary of airports contains 2 items."(这个字典有两个数据项)
if airports.isEmpty {
    print("The airports dictionary is empty.")
} else {
    print("The airports dictionary is not empty.")
}
// 打印 "The airports dictionary is not empty."
airports["LHR"] = "London"
// airports 字典现在有三个数据项
airports["LHR"] = "London Heathrow"
// “LHR”对应的值被改为“London Heathrow”
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
    print("The old value for DUB was \(oldValue).")
}
// 输出 "The old value for DUB was Dublin."
if let airportName = airports["DUB"] {
    print("The name of the airport is \(airportName).")
} else {
    print("That airport is not in the airports dictionary.")
}
// 打印 "The name of the airport is Dublin Airport."
airports["APL"] = "Apple Internation"
// "Apple Internation" 不是真的 APL 机场,删除它
airports["APL"] = nil
// APL 现在被移除了
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.")
}
// prints "The removed airport's name is Dublin Airport."
5、字典遍历
for (airportCode, airportName) in airports {
    print("\(airportCode): \(airportName)")
}
// YYZ: Toronto Pearson
// LHR: London Heathrow
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
上一篇 下一篇

猜你喜欢

热点阅读