Swift 中的集合 (Set)

xiaoxiao2021-02-28  66

Set

Set 用来存储相同类型并且没有明确的顺序的值,与数组不同的是,Set里面的元素是无序的,并且每个元素都不能重复Set 类型的基本格式为: Set<Element>()

创建 Set

创建一个空的Set let letters = Set<Character>() 通过数组创建Set let favorites : Set<String> = ["红色","绿色","蓝色"] 如果数组中所有元素的类型相同,则Set 中元素的类型无需显式写出,可由系统自动判断推出 var favoriteColor : Set = ["红色","绿色","蓝色"]

访问修改 Set

获取 Set 中的元素个数 var colors : Set = ["1","2","3"] let count = colors.count

输出

Set 增 删 查

var colors : Set = ["1","2","3"] 增加 colors.insert("4")

输出

查询 colors.contains("1")

输出

删除

删除指定某个元素

colors.remove("2")

输出

删除第一个 colors.removeFirst() 删除所有 colors.removeAll()

遍历 Set

//遍历Set var colors1 : Set = ["red","blue","white"] //无序遍历 for color in colors1 { print(color) }

输出

//有序遍历 for color in colors1.sorted() { print(color) }

输出

Set 之间的操作

let animals1 : Set = ["dog","cat","tiger","fish"] let animals2 : Set = ["dog","tiger","bird"] 根据两个Set 共同的值创建一个新的Set let animals3 : Set = animals1.intersection(animals2)

输出

根据两个Set 不同的值创建一个新的Set let animals4 : Set = animals1.symmetricDifference(animals2)

输出

根据两个Set 中的所有值创建一个新的Set let animals5 : Set = animals1.union(animals2)

输出

根据 animals1 包含但是 animals2 不包含的值创建一个新的Set let animals6 : Set = animals1.subtracting(animals2)

输出

Set 之间的关系

Swift 中提供了操作符和方法来判断 Set 之间的关系 是否相等 运算符 “==” 判断两个Set 的值是否全部相等

首先创建 Set let a : Set = [1,2,3,4,5] let b : Set = [1,2] let c : Set = [4,5,6,7,8] let d : Set = [1,2] 判断b 中的值是否都被 a包含 print(b.isSubset(of: a)) 判断a 是否包含 b 中的所有值 print(a.isSuperset(of: b)) 判断 c 是不是 d 的子集 并且两个 Set 不相等 print(c.isStrictSubset(of: d)) 判断 c 是不是 d 的父集 并且两个 Set 不相等 print(c.isStrictSuperset(of: d)) 判断 c 和 d 没有有交集 (不含有相同的值) print(c.isDisjoint(with: d))
转载请注明原文地址: https://www.6miu.com/read-85817.html

最新回复(0)