首页 > 代码库 > Swift学习笔记(5):集合类型

Swift学习笔记(5):集合类型

目录:

  • 数组:Array
  • 集合:Set
  • 字典:Dictionary

Swift提供Array(有序集合数据)、Set(无序无重复集合)和Dictionary(无序键值对集合)三种基本集合类型来存储明确数据类型的集合数据。

使用var将集合声明为变量,可以在创建之后添加、移除、修改集合内数据项。如果使用let将集合声明为常量,则它的大小和内容就都不可改变。

 

数组:Array

初始化和赋值:

var someInts = [Int]()      // 创建指定数据类型的空数组someInts = []               // 为已知数据类型的数据赋空值// threeDoubles 是一种 [Double] 数组,等价于 [0.0, 0.0, 0.0]var threeDoubles = Array(repeating: 0.0, count: 3)  // 创建带有默认值的数据// sixDoubles 被推断为 [Double],等价于 [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]var anotherThreeDoubles = Array(repeating: 2.5, count: 3)var sixDoubles = threeDoubles + anotherThreeDoubles // 通过+组合两个相同数据类型数组var shoppingList = ["Eggs", "Milk"]                 // 数组字面量构造数组var shoppingList: [String] = ["Eggs", "Milk"]       // 与上面等价

我们可以使用下标或属性和方法来访问和修改数组:

shoppingList.count               // 获取数组元素个数// 使用isEmpty属性判断数组书否为空if shoppingList.isEmpty {    print("The shopping list is empty.")}shoppingList.append("Flour")     // 使用append()方法追加数据元素shoppingList += ["Chocolate Spread", "Cheese", "Butter"]  // 使用+=追加数据元素var firstItem = shoppingList[0]  // 使用数组下标访问元素,第一项是"Eggs"shoppingList[0] = "Six eggs"     // 使用下标改变数组元素shoppingList[4...6] = ["Bananas", "Apples"]  // 将4~6的3个元素替换为右边的2个元素shoppingList.insert("Maple Syrup", at: 0)    // 使用insert(_:at:)方法在具体索引之前添加元素let mapleSyrup = remove(at: 0)   // 移除制定索引的数组元素let apples = shoppingList.removeLast()       // 移除数组最后一项元素

注意:

?不可以用下标访问的形式去在数组尾部添加新项
?数组起始索引为0,最大索引为 count-1

使用for-in遍历数组:

for item in shoppingList {    print(item)}

使用数组enumerated()方法遍历数组返回元素值和索引:

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

  

集合:Set

一种类型的数据需要存储在Set中,该类型必须是可哈希的,哈希值类型为Int。Swift基本数据类型都可哈希,没有关联值的枚举也可哈希。

自定义数据类型要作为Set元素保存时,必须实现Swift语言的Hashable和Equatable协议。 

初始化和赋值:

var letters = Set<Character>() // 创建一个空Sets集合letters = []                   // 已知数据类型,赋值一个空Sets集合, letters依然是Set<Character>类型// 使用数组字面量构造一个集合var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"] 

访问和修改Set集合:

favoriteGenres.count          // 获取Set集合的元素个数// 使用isEmpty属性判断Set集合是否为空if favoriteGenres.isEmpty {    print("As far as music goes, I‘m not picky.")}favoriteGenres.insert("Jazz") // 插入一个Set集合元素let removedGenre = favoriteGenres.remove("Rock")   // 删除一个Set集合元素favoriteGenres.removeAll()    // 删除集合所有元素// 使用contains()方法判断Set集合是否包含指定元素if favoriteGenres.contains("Funk") {    print("I get up on the good foot.")}

使用for-in遍历Set集合:

for genre in favoriteGenres {    print("\(genre)")}

使用sorted()返回一个已排序的数字来遍历Set集合:

for genre in favoriteGenres.sorted() {     print("(genre)")}// prints "Classical"// prints "Hip hop"// prints "Jazz

 

字典:Dictionary

初始化和赋值:

var namesOfIntegers = [Int: String]  // 创建一个空字典namesOfIntegers = [:]                // 给已知数据类型字典赋空值// 字面量构造一个字典var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

访问和修改Dictionary集合:

airports.count              // 获取字典元素个数// 判断字典是否为空if airports.isEmpty {    print("The airports dictionary is empty.")}airports["LHR"] = "London"  //使用下标为指定key字典元素赋值或变更值// 使用字典的updateValue()方法更新字典元素并检验更新结果if let oldValue = http://www.mamicode.com/airports.updateValue("Dublin Airport", forKey: "DUB") {     print("The old value for DUB was (oldValue).")}// 判断字典中是否存在指定key关联元素if let airportName = airports["DUB"] {    print("The name of the airport is (airportName).")}airports["APL"] = nil        // 删除字典指定key关联的元素// 使用字典removedValue()方法删除指定元素并检验删除结果if let removedValue = http://www.mamicode.com/airports. removeValue(forKey: "DUB") {    print("The removed airport‘s name is (removedValue).")}

使用for-in遍历字典:

for (airportCode, airportName) in airports {    print("(airportCode): (airportName)")}// YYZ: Toronto Pearson// LHR: London Heathrow

通过访问keys或者values属性,我们也可以遍历字典的键或者值:

for airportCode in airports.keys {     print("Airport code: (airportCode)")}// Airport code: YYZ// Airport code: LHRfor airportName in airports.values {    print("Airport name: (airportName)")}// Airport name: Toronto Pearson// Airport name: London Heathrow

 

 

声明:该系列内容均来自网络或电子书籍,只做学习总结!

Swift学习笔记(5):集合类型