基础知识五:集合(Sets)

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

1.定义

//空集合
var tempSet = Set<Character>()

//字面量创建
var tempSet1 :Set<String> = ["a","b","c"]
var tempSet2 :Set = ["a","b","c"]

2.长度

var tempSet3 :Set = ["a","b","c"]
print(tempSet3.count)  //3

3.是否为空

var tempSet4 :Set<String> = []
if tempSet4.isEmpty{
    print("集合为空")  //集合为空
}

4.增

若插入的元素在集合有,则集合不变;若插入的元素集合中没有,则添加
var tempSet3 :Set = ["a","b","c"]
tempSet3.insert("a")
print(tempSet3) //["b", "a", "c"]

tempSet3.insert("d")
print(tempSet3) //["b", "a", "d", "c"]

5.删

 删除元素,并返回对应的元素;若集合中没有,则返回nil
var tempSet3 :Set = ["a","b","c","d"]
tempSet3.remove("d")
print(tempSet3) // ["b", "a", "c"]

6.查

var tempSet3 :Set = ["a","b","c","d"]
if tempSet3.contains("b"){
    print("集中中有 b 元素")
}

7.遍历

var tempSet3 :Set = ["a","b","c"]
for item in tempSet3{
    print("\(item)")
}
//b
//a
//c

8.排序

为了按照特定顺序来遍历一个Set中的值可以使用sorted()方法,
它将返回一个有序数组,这个数组的元素排列顺序由操作符'<'对元素进行比较的结果来确定.
var tempSet3 :Set = ["b","c","a"]
for item in tempSet3.sorted(){
    print("\(item)")
}
//a
//b
//c

9.集合之间的操作

使用intersection(_:): 交集
使用union(_:): 并集
使用symmetricDifference(_:)方法根据在一个集合中但不在两个集合中的值创建一个新的集合。
使用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]

10.集合成员关系和相等

使用“是否相等”运算符(==)来判断两个集合是否包含全部相同的值。
使用isSubset(of:)方法来判断一个集合中的值是否也被包含在另外一个集合中。
使用isSuperset(of:)方法来判断一个集合中包含另一个集合中所有的值。
使用isStrictSubset(of:)或者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

极客学院 - 集合

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前面已经介绍完了Collection接口下的集合实现类,今天我们来介绍Map接口下的两个重要的集合实现类HashM...
    Ruheng阅读 10,505评论 2 38
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,503评论 25 709
  • 集合框架体系概述 为什么出现集合类?方便多个对象的操作,就对对象进行存储,集合就是存储对象最常用的一种方法. 数组...
    acc8226阅读 804评论 0 1
  • 看下面的实例: 通常我们使用内置的type创建的类型会使用dict来存储不同的属性和方法。因为字典时无序的,所以属...
    第八共同体阅读 798评论 0 0
  • 孔子名丘,字仲尼。春秋末期鲁国陬邑(山东曲阜)人,出身于没落的宋国贵族家庭,刻苦好学。曾从事「儒」(贵族丧...
    李宣成阅读 622评论 0 0