Swift-集合

2018-01-10  本文已影响0人  qtoq126
  1. 集合的初始化
var skillsOfA: Set<String> = ["swift", "oc", "oc"] //集合中的每一个值都是唯一的
var skillsOfB: Set = ["HTML", "CSS", "Ruby"]

var emptySet1: Set<Double> = []
var emptySet2 = Set<Int>()

var vowels = Set(["A", "E", "I", "O", "U"])
  1. 集合的成员变量
let set: Set = [3, 2, 2, 1]
set.count
emptySet1.isEmpty

skillsOfA.first // 取出一个元素

skillsOfA.contains("swift")
  1. 遍历
//遍历
for skill in skillsOfA {
    print(skill)
}
//字典比较
let a: Set = [1, 2, 3, 4]
let b: Set = [1, 3, 2, 1, 1, 4, 2, 3, 2]
a == b // true
  1. 集合的增删改查
var skillsOfA: Set = ["swift", "oc"]
//增
skillsOfA.insert("python")
skillsOfA.insert("swift") // 无效
//删
skillsOfA.remove("oc") //返回被删除元素
if let skill = skillsOfA.remove("oc") { //解包
    print("oc is removed")
}
  1. 集合中的数学方法
var skillsOfA: Set = ["swift", "oc"]
var skillsOfB: Set = ["HTML", "CSS", "Ruby"]
var skillsOfC: Set = ["swift", "HTML", "CSS"]

//并集
skillsOfA.union(skillsOfB) //不改变原集合
skillsOfA.formUnion //改变原集合
//交集
skillsOfA.intersection(skillsOfC) //不改变原集合
skillsOfA.formIntersection(skillsOfC) //改变原集合
//减集
skillsOfA.subtract(skillsOfC) //在A中减去跟C集合相同的元素
skillsOfC.subtract(skillsOfA) //在C中减去跟A集合相同的元素
//子集、真子集
var skillsOfD: Set = ["swift", "oc"]
skillsOfD.isSubset(of: skillsOfA) //判断D是不是A的子集 true
skillsOfD.isStrictSubset(of: skillsOfA) //判断D是不是A的真子集 false
//超集、真超集
skillsOfA.isSuperset(of: skillsOfD) //判断D是不是A的超集 true
skillsOfA.isStrictSuperset(of: skillsOfD) //判断D是不是A的真超集 false
//判断两个集合是否是相离的
skillsOfA.isDisjoint(of: skillsOfB) //true
上一篇下一篇

猜你喜欢

热点阅读