Swift - 容器:数组 | 字典 | 集合

前言

1 - Swift 提供数组、集合和字典三种基本的集合类型用来存储集合数据,它们三者被实现为泛型集合:数组是有序数据的集;集合是无序无重复数据的集;字典是无序的键值对的集!注:Swift 中集合类型都是值类型;OC 里都是引用类型

2 - Swift 中同样使用引用计数的概念来管理内存,但是引用计数只是用于对象类型,而值类型不需要管理

数组

1 - 初始化

复制代码
// 方式一:构造语法创建数组
var someInts = [Int]()// 使用构造函数,someInts 的值类型被推断为 [Int]
someInts.append(3)
print(someInts) // [3]
// 可以使用空数组语句创建一个空数组
someInts = []   // 现在成了空数组
print(someInts) // []


// 方式二:指定大小并且赋初始值
var threeDoubles = Array(repeating: 1.0, count: 3) // 等价于 [1.0, 1.0, 1.0]


// 方式三:使用字面量创建
var shoppingList01: [String] = ["elephant", "lion"]
// 使用字面量构造拥有相同类型值数组的时不必把数组的类型定义清楚
var shoppingList02 = ["cat", "dog"]
复制代码

2 - 增、删、改、查 | 遍历

复制代码
 1 // +:组合相同类型数组
 2 var threeDoubles = Array(repeating: 1.0, count: 3)
 3 var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
 4 var sixDoubles = anotherThreeDoubles + threeDoubles
 5 print(sixDoubles)// [2.5, 2.5, 2.5, 1.0, 1.0, 1.0]
 6 
 7 var shoppingList: [String] = ["Eggs", "Milk"]
 8 // isEmpty 是否为空
 9 if shoppingList.isEmpty {
10 
11 }else{
12 
13     // count
14     print(shoppingList.count) // 6
15     // 根据下标获取元素
16     shoppingList[0] = "Bread"
17     shoppingList.append("Chocolate")
18     shoppingList.append("Noodle")
19     shoppingList.append("Peanut")
20     print(shoppingList)// ["Bread", "Milk", "Chocolate", "Noodle", "Peanut"]
21 }
22 
23 // 即使新数据和原有数据的数量是不一样,同样可以达到修改的目的
24 // 下标 1-4 的数据元素被替换成 ["Bananas", "Apples"]
25 shoppingList[1...4] = ["Bananas", "Apples"]// ["Bread", "Bananas", "Apples"]
26 
27 // insert
28 shoppingList.insert("Apple", at: 0)//["Apple", "Bread", "Bananas", "Apples"]
29 
30 // remove:删除并返回这个被移除的数据项
31 let seeYouWhat = shoppingList.remove(at: 1) // ["Apple","Bananas", "Apples"]
32 print(seeYouWhat)// Bread
33 
34 // removeLast
35 shoppingList.removeLast() // ["Apple", "Bananas"]
36 
37 //-------------------------------------
38 
39 // 数组遍历
40 // for ... in ...
41 for item in shoppingList {
42     print(item)
43     // Apple
44     // Bananas
45 }
46 
47 // enumerated() 返回一个由索引值、数据值组成的元组数组
48 for (index, value) in shoppingList.enumerated() {
49     print("Item \(index): \(value)")
50 }
51 // Item 0: Apple
52 // Item 1: Bananas
53 
54 // removeAll
55 shoppingList.removeAll()  // []
复制代码

集合

1 - 集合和数组不同的是,集合没有等价的简化形式。一个类型为了存储在集合中,该类型必须是可哈希化的。一个哈希值是 Int 类型的,相等对象的哈希值必须相同,比如 a == b 那么 a.hashValue == b.hashValue。Swift 的所有基本类型默认都是可哈希化的

① 初始化、增删 | 遍历

复制代码
 1 // 方式一:构造器语法
 2 var letters = Set<Character>()
 3 letters.insert("a")// ["a"]
 4 // 通过一个空的数组字面量创建一个空的集合
 5 letters = []
 6 print(letters)// []
 7 
 8 // 方式二:数组字面量来构造集合
 9 var favoriteGenres1: Set<String> = ["Rock", "Classical", "Hip hop"]
10 var favoriteGenres2: Set = ["1", "2", "4"]
11 
12 // count
13 favoriteGenres2.count
14 // isEmpty
15 favoriteGenres2.isEmpty
16 // insert
17 favoriteGenres2.insert("100")
18 
19 // remove 删除一个元素
20 // 删除它并且返回它的值; 注:如果该集合不包含它,则返回 nil
21 let removedGenre = favoriteGenres2.remove("Rock")
22 print(removedGenre)// nil
23 
24 // removeAll
25 favoriteGenres1.removeAll()// []
26 
27 // contains
28 let isContained: Bool = favoriteGenres2.contains("100") // true
29 
30 //---------------------------------
31 
32 for genre in favoriteGenres2 {
33     print(genre)
34 }
35 /* 遍历结果如下:没有确定的顺序
36  * 2
37  * 4
38  * 1
39  * 100
40  **/
41 
42 // 为了按照特定顺序来遍历一个集合中的值可以使用 sorted() 方法
43 // 它将返回一个有序数组
44 for genre in favoriteGenres2.sorted() {
45    print(genre)
46 }
47 /* 遍历结果如下
48 * 1
49 * 100
50 * 2
51 * 4
52 **/
复制代码

② 集合操作

复制代码
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()
// []

// 去掉 singleDigitPrimeNumbers 中的元素
oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
// [1, 9]

// 去掉交集的集合
oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()
// [1, 2, 9]
复制代码

③ 集合成员的关系

复制代码
 1 let houseAnimals: Set = ["🐶", "🐱"]
 2 let farmAnimals:  Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
 3 let cityAnimals:  Set = ["🐦", "🐭"]
 4 let cityAnimals2:  Set = ["🐦", "🐭"]
 5 
 6 // 子集合
 7 houseAnimals.isSubset(of: farmAnimals)   // true
 8 // 父集合
 9 farmAnimals.isSuperset(of: houseAnimals) // true
10 // 是否存在交集
11 farmAnimals.isDisjoint(with: cityAnimals) // true
12 
13 // 是否为子集合且两者不相等
14 houseAnimals.isStrictSubset(of: farmAnimals) // true
15 cityAnimals.isStrictSubset(of: cityAnimals2) // false
16 
17 cityAnimals.isSubset(of: cityAnimals2)  // true
18 cityAnimals.isSuperset(of: cityAnimals2)// true
复制代码

字典

1 - 字典是一种无序的集合,它存储的是键值对之间的关系。所有键的值需要是相同的类型,所有值的类型也需要相同

① 初始化

复制代码
// 方式一:构造语法创建
var namesOfIntegers = [Int: String]()
// 赋值:包含一个键值对
namesOfIntegers[16] = "sixteen"
print(namesOfIntegers) // [16: "sixteen"]
// 空值
namesOfIntegers = [:]  // [:]
print(namesOfIntegers)

// 方式二:使用字典字面量来构造字典
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
var airports1 = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
复制代码

② 访问、修改 | 遍历

复制代码
 1 var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
 2 // count
 3 airports.count
 4 // isEmpty
 5 airports.isEmpty
 6 // 添加
 7 airports["LHR"] = "London"
 8 print(airports)
 9 // ["LHR": "London", "YYZ": "Toronto Pearson", "DUB": "Dublin"]
10 
11 // 修改
12 airports["LHR"] = "London Heathrow"
13 // updateValue 更新数据的同时会返回旧值,且返回的值是可选类型
14 if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
15     print(oldValue)// Dublin
16 }
17 
18 // 根据 key 返回 value。返回值同样是可选类型
19 let airportName = airports["DUB"]
20 
21 // 移除
22 airports["DUB"] = nil // DUB = Dublin 被移除
23 // removeValue 移除并返回旧值
24 let removedValue = airports.removeValue(forKey: "DUB")// nil
25 
26 //--------------------------------------------
27 
28 // 遍历:每一个字典中的数据项都以 (key, value) 元组形式返回
29 for (airportCode, airportName) in airports {
30     print("\(airportCode) = \(airportName)")
31 }
32 /* 遍历结果
33  * YYZ = Toronto Pearson
34  * LHR = London Heathrow
35  */
36 
37 // keys、values
38 for airportCode in airports.keys{
39     print("\(airportCode)")
40 }
41 /* 遍历结果
42  * YYZ
43  * LHR
44  */
45 
46 for airportName in airports.values{
47     print("\(airportName)")
48 }
49 /* 遍历结果
50  * Toronto Pearson
51  * London Heathrow
52  */
53 
54 // 字典是无序集合类型,为了以特定的顺序遍历字典的键或值,可使用 sorted() 方法
55 let airportCodes = [String](airports.keys.sorted())
56 print(airportCodes) // ["LHR", "YYZ"]
57 let airportNames = [String](airports.values)
58 print(airportNames) // ["Toronto Pearson", "London Heathrow"]
复制代码

 

posted on   低头捡石頭  阅读(69)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

导航

统计

点击右上角即可分享
微信分享提示