Swift--Set的了解

1. 创建和初始化一个空的set

var letters = Set<Character>()

或者,如果上下文已经提供了类型信息,例如函数参数或已输入的变量或常量,则可以创建空的集合,其中包含空数组文本:

letters.insert("a")
// letters now contains 1 value of type Character
letters = []
// letters is now an empty set, but is still of type Set<Character>

 

2.创建一个带有数组literal的集合

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

 集合类型不能仅从数组文字推断,因此类型集必须显式声明。然而,因为Swift类型推断,如果你用一个相同类型的数组值去初始化集合时,不需要对集合设置类型。例如上面的那个例子,可以写成如下:

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

 

3.获取和修改集合的值

你可以通过set的相关方法和属性来修改和获取到集合的值

<1>用 只读属性 count来获取一个集合的个数

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

<2> 用 isEmpty这个布尔值的属性来检查 count这个属性的值是否等于0

if favoriteGenres.isEmpty {
    print("As far as music goes, I'm not picky.")
} else {
    print("I have particular music preferences.")
}

 <3>你可以调用insert(:)这个方法来对集合插入一个新的值

favoriteGenres.insert("Jazz")

 <4>你可以用 remove(:)这个方法删除集合中的某个值,如果这个值存在的话,返回删除后的值,如果不存在的话,返回nil。调用removeAll(), 可以删除集合中的全部元素;用contains(_:)判断是否包含某个值

if let removedGenre = favoriteGenres.remove("Rock") {
    print("\(removedGenre)? I'm over it.")
} else {
    print("I never much cared for that.")
}
// Prints "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.")
}
// Prints "It's too funky in here."

 <5>用for-in 来遍历一个集合的值

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

 在Swift中,Set类型是无序的,如果想按顺序遍历集合,用sorted()方法排序,该方法 按照从小到大的顺序排列后,以一个数组为元素返回。

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

 

4.操作类型的集合

你可以有效地执行基本的集合操作,例如将两个集合组合在一起,确定两个集合有共同的值,或者确定两个集合是否包含了所有的、一些或者没有相同的值。

 调用intersection(_:)方法用两个集合的相同元素生成一个新的集合;

调用symmetricDifference(_:)方法表示:用两个集合中的不同元素生成一个新的集合;

调用union(_:)方法表示:用两个集合的全部元素生成一个集合(该集合中,相同的值只保留一个)

调用subtracting(_:)方法表示:去除集合a中与集合b中相同的元素,生成一个新的集合

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]

 

5.集合间的元素关系与相等

用“==”号判断两个集合的值是否一致;

用isSubset(of:)方法判断集合中的所有值是否包含在指定集合中;

用isSuperset(of:)方法判断一个集合是否包含指定集合中的所有值;

用 isStrictSubset(of:) or isStrictSuperset(of:)方法判断一个集合是否是指定集合的子集合或父集合;

用 isDisjoint(with:)方法来判断两个集合是否没有共同值;

let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
let cityAnimals: Set = ["🐦", "🐭"]
 
houseAnimals.isSubset(of: farmAnimals)
// true
farmAnimals.isSuperset(of: houseAnimals)
// true
farmAnimals.isDisjoint(with: cityAnimals)
// true

 

posted @ 2017-11-16 23:06  一人前行  阅读(963)  评论(0编辑  收藏  举报