美文网首页
Swift中的集合类型

Swift中的集合类型

作者: keisme | 来源:发表于2017-05-11 03:30 被阅读58次

Swift提供ArraysSetsDictionaries三种基本的集合类型用来存储集合数据。

1. 数组

数组使用有序列表存储同一类型的多个值,相同的值可以多次出现。

1.1 创建一个空数组

var someInts = [Int]()

1.2 创建一个带有默认值得数组

var threeDoubles = Array(repeating: 0.0, count: 3)
// 等价于[0.0, 0,0, 0.0]

1.3 通过两个数组相加创建一个数组

var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
var sixDoubles = threeDoubles + anotherThreeDoubles
// sixDoubles被推断为[Double]

1.4 用数组字面量构造数组

var shoppingList:[String] = ["Eggs", "Milk"]
// shoppingList已经被构造并且拥有两个初始项

由于Swift的类型推断机制,当我们用字面量构造只拥有相同类型值数组的时候,可以省却数组的类型:

var shoppingList = ["Eggs", "Milk"]

1.5 访问和修改数组

  • count:获取数组中的元素数目
  • isEmpty:检查count是否为0
  • append(_:):在数组后面添加新的数据
  • insert(_:at:):在某个具体索引值之前添加数据项
  • remove(at:):移除数组中的某一项
  • removeLast():移除数组的最后一项

+=运算符可以直接在数组后面添加一个或多个同类型的数据项:

shoppingList += ["Baking Powder"]
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]

我们可以通过下标获取或改变某个已有索引值对应的数据。
还可以利用下标来一次改变一系列的数据值:

shoppingList[4..<6] = ["Bananas", "Apples"]

1.6 数组的遍历

我们可以用for-in循环遍历所有数组中的数据项。
如果我们同时需要每个数据项的值和索引值,可以使用enumerated()方法。enumerated()返回一个由每一个数据项索引值和数据值组成的元组:

for (index, value) in shoppingList.enumerated() {
    print("Item \(String(index + 1)): \(value)")
}

2. 集合

集合用来存储相同类型并且没有确定顺序的值,集合内的元素不能重复。

2.1 集合类型的哈希值

存储在集合中的类型必须是可哈希化的,Swift的所有基本类型(比如String,Int,DoubleBool)默认都是可哈希化的,没有关联值额枚举成员值默认也是可哈希化的。

你可以使用自定义的类型作为集合的值的类型或字典的键的类型,但需要使自定义类型符合Swift标准库中的Hashable协议。符合Hashable协议的类型需要提供一个类型为Int的可读属性hashValue

2.2 集合类型语法

2.2.1 创建和构造一个空的集合

var letters = Set<Character>()

2.2.2 用数组字面量创建集合

var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]

2.2.3 访问和修改一个集合

  • count:返回Set中元素的数量
  • isEmpty:检查count是否为0
  • insert(_:):添加一个新元素
  • remove(_:):删除一个元素(如果Set不包含该值,返回nil)
  • removeAll():删除所有元素
  • contains(_:):检查Set中是否包含一个特定的值

2.2.4 遍历一个集合

使用for-in遍历一个集合。
Swift的Set类型没有确定的顺序,为了按照特定的顺序来遍历一个Set中的值可以用sorted()方法,它将返回一个有序数组,这个数组的元素排列顺序又操作符<对元素进行比较的结果来确定 。

for genre in favoriteGenres.sorted() {
    print("genre")
}
// 按顺序打印"Classical", "Hip hop", "Jazz"

2.3 集合操作

2.3.1 基本集合操作

  • intersection(_:):根据两个集合中都包含的值创建一个新的集合
  • symmetricDifference(_:):根据在一个集合中但不在两个集合中的值创建一个新集合
  • union(_:):根据两个集合的值创建一个新集合
  • subtracting(_:):根据不在该集合中的值创建一个新集合
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]

2.3.2 集合成员关系和相等

  • ==:判断两个集合是否相等
  • isSubset(of:):判断一个集合中的值是否也被包含在另一个集合中
  • isStrictSubset(of:)/isStrictSuperset(of:):判断一个集合是否是另一个集合的子集合/父集合并且两个集合不相等
  • isDisjoint(with:):判断那两个集合是否有交集
let houseAnimals: Set = ["dog", "cat"]
let farmAnimals: Set = ["cow", "chicken", "sheep", "dog", "cat"]
let cityAnimals: Set = ["bird", "mouse"]

houseAnimals.isSubset(of: farmAnimals)
// true

farmAnimals.isSuperset(of: houseAnimals)
// true

farmAnimals.isDisjoint(with: cityAnimals)
// ture

3. 字典

字典是一种存储多个相同类型的值得容器,字典中的数据项没有具体顺序。

3.1 创建一个空字典

var namesOfIntegers = [Int: String]()

3.2 用字典字面量创建字典

var airports: [String: String] = ["XYZ": "Toronto Pearson", "DUB": "Dublin"]

var airports = ["XYZ": "Toronto Pearson", "DUB": "Dublin"]

3.3 访问和修改字典

同数组和集合一样,字典同样具有countisEmpty属性。
我们可以在字典中使用下表语法添加新的数据项,或者改变特定键对应的值。

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)")
}
// 输出 "The old value for DUB was Dublin

我们也可以使用下标语法在字典中检索特定键对应的值。

if let airportName = airports["DUB"] {
    print("The name of the airports is \(airportName)")
} else {
    print("That airport is not in the airports dictionary")
}
// 打印 "The name of the airports is Dublin Airport"

我们还可以使用下标语法通过给某个键的对应值赋值为nil来从字典里移除一个键值对:

airports["APL"] = "Apple Internation"
airports["APL"] = nil

removeValue(forKey:)方法也可以用来移除键值对,返回被移除的值或者在没有值得情况下返回nil

if let removedValue = airports.removeValue(forKey: "DUB") {
    print("The removed airports name is \(removedValue)")
} else {
    print("The airports dictionary does not contain a value for DUB")
}
// prints "The removed airports name is Dublin Airport"

3.4 字典遍历

除了for-in玄幻遍历,我们也可以通过访问keys或者values属性,遍历字典的键或者值:

Swift的字典类型是无序集合类型,为了以特定的顺序遍历字典的键或值,可以对字典的keysvalues属性使用sorted()方法。

相关文章

  • Swift语法--集合类型

    集合类型 提供三种集合,数组、合集、字典。Swift中的集合总是明确能储存的值的类型。 Swift中的集合是采用泛...

  • iOS开发 - 「Swift 学习」Dictionary集合类型

    Swift语言Dictionary集合类型的创建、遍历 Swift 的字典类型是无序集合类型 Dictionary...

  • Swift -- 集合类型

    Swift 集合类型 Swift 语言提供Arrays、Sets和Dictionaries三种基本的集合类型用来存...

  • 第二十九章 Swift 泛型

    Swift 提供了泛型让你写出灵活且可重用的函数和类型。 1. 集合类 在Swift的集合类中,元素类型是必须指定...

  • Swift基础知识补充(三)

      1、集合类型   Swift中的集合类型主要是指Array、Dictionary和Set,详细情况参见《Swi...

  • Swift3.0集合类型(Collection Types)

    Swift一样有着三种基本集合类型,数组,集合,字典。 在Swift中,这三种类型总是很明确要存储的类型,这意味着...

  • Swift中的集合类型

    Swift提供Arrays、Sets和Dictionaries三种基本的集合类型用来存储集合数据。 1. 数组 数...

  • 从零开始Swift之集合

    Swift中提供了三种主要的集合类型,Array,Sets,Dictionary Array Swift数组中的值...

  • Swift:基础(十四)字典

    Swift 字典 Swift 字典用来存储无序的相同类型数据的集合,Swift 字典会强制检测元素的类型,如果类型...

  • Swift3.x - 集合类型

    集合类型的介绍Swift中提供三种集合类型:数组(Arrays)、集合(Sets)和字典(Dictionaries...

网友评论

      本文标题:Swift中的集合类型

      本文链接:https://www.haomeiwen.com/subject/bumntxtx.html