Swift 集合(Set)

2019-05-06  本文已影响0人  黎明s

demo链接:
https://share.weiyun.com/5VRfIYP
参考链接:
http://www.swift51.com/swift4.0/chapter2/04_Collection_Types.html#sets

集合(Set)用来存储相同类型并且没有确定顺序的值。当集合元素顺序不重要时或者希望确保每个元素只出现一次时可以使用集合而不是数组。

注意:
Swift的Set类型被桥接到Foundation中的NSSet类。
关于使用FoundationCocoaSet的知识,参见 Using Swift with Cocoa and Obejective-C(Swift 3.0.1)使用 Cocoa 数据类型部分。

创建一个空集合

你可以通过构造器语法创建一个特定类型的空集合:

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变量的类型被推断为Set<Character>

此外,如果上下文提供了类型信息,比如作为函数的参数或者已知类型的变量或常量,我们可以通过一个空的数组字面量创建一个空的Set

letters.insert("a")
// letters 现在含有1个 Character 类型的值
letters = []
// letters 现在是一个空的 Set, 但是它依然是 Set<Character> 类型

用数组字面量创建集合

你可以使用数组字面量来构造集合,并且可以使用简化形式写一个或者多个值作为集合元素:

var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres 被构造成含有三个初始值的集合

这个favoriteGenres变量被声明为一个String值的集合,写为Set<String>。由于这个特定的集合含有指定String类型的值,所以它只允许存储String类型值。这里的favoriteGenres变量有三个String类型的初始值("Rock","Classical"和"Hip hop"),并以数组字面量的方式出现。

一个Set类型不能从数组字面量中被单独推断出来,因此Set类型必须显式声明。然而,由于 Swift 的类型推断功能,如果你想使用一个数组字面量构造一个Set并且该数组字面量中的所有元素类型相同,那么你无须写出Set的具体类型。favoriteGenres的构造形式可以采用简化的方式代替:

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

由于数组字面量中的所有元素类型相同,Swift 可以推断出Set<String>作为favoriteGenres变量的正确类型。

访问和修改一个集合

为了找出一个Set中元素的数量,可以使用其只读属性 count

print("I have \(favoriteGenres.count) favorite music genres.")
// I have 3 favorite music genres.

使用布尔属性isEmpty作为一个缩写形式去检查count属性是否为0:

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.

可以通过调用Setinsert(_:)方法来添加一个新元素:

favoriteGenres.insert("Jazz")
// favoriteGenres 现在包含4个元素

可以通过调用Set的remove(_:)方法去删除一个元素,如果该值是该Set的一个元素则删除该元素并且返回被删除的元素值,否则如果该Set不包含该值,则返回nil。另外,Set中的所有元素可以通过它的removeAll()方法删除。

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.

使用contains(_:)方法去检查Set中是否包含一个特定的值:

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.

遍历一个集合

你可以在一个for-in循环中遍历一个Set中的所有值。

for genre in favoriteGenres {
    print("\(genre)")
}
// Classical
// Jazz
// Hip hop

更多关于for-in循环的信息,参见For 循环

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

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

基本集合操作

下面的插图描述了两个集合-a和b-以及通过绿色区域显示集合各种操作的结果。
https://share.weiyun.com/5AHBZ4j

SetsOperationResult.png
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]

集合成员关系和相等

下面的插图描述了三个集合a,b和c,以及通过重叠区域表述集合间共享的元素。集合a是集合b的父集合,因为a包含了b中所有的元素,相反的,集合b是集合a的子集合,因为属于b的元素也被a包含。集合b和集合c彼此不关联,因为它们之间没有共同的元素。
https://share.weiyun.com/5Grm1OD

SetsRelationship.png
let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
let cityAnimals: Set = ["🐦", "🐭"]

houseAnimals.isSubset(of: farmAnimals)
// true
farmAnimals.isSuperset(of: houseAnimals)
// true
farmAnimals.isDisjoint(with: cityAnimals)
// true
上一篇下一篇

猜你喜欢

热点阅读