首页 > 代码库 > swift集合

swift集合

swift的集合与数组比较相近,最大的区别在于集合无序,并且所含有的元素不能重复

1、集合的定义

//集合定义
var skillsOfA:Set<String> = ["swift","OC"]


//集合是无序的,会自动删除重复的元素值
var skillsOfB:Set<String> = ["swift","OC","OC"]

//空集合

var emptySet1:Set<Int> = []

var emptySet2 = Set<Double>()

2、集合的基本使用方法

//集合与数组的转换

var vowels = Set(["A","E","I","O","U","U"])

var skillsOfC:Set = ["swift","OC","OC"]

//集合的个数
skillsOfA.count

//判断集合是否为空
emptySet1.isEmpty

//随机取出一个元素(因为集合是无序的,所以没有第一个值)
skillsOfA.first

//判断集合是否包含
skillsOfA.contains("swift")

//遍历集合里面的元素
for skill in skillsOfA {
    print(skill)
}


//判断两个集合是否相等
let setA: Set = [1,2,3]
let setB: Set = [2,2,3,1,1,1,1,1]

setA == setB

3、集合的增加删除操作

var skillsOfAA:Set<String> = ["swift","OC"]
var skillsOfBB:Set<String> = ["HTML","CSS","Javascript"]
var skillsOfCC:Set<String> = []

//集合添加元素
skillsOfCC.insert("swift")
skillsOfCC.insert("OC")
skillsOfCC.insert("CSS")

//集合移除元素(返回被移除的元素)
skillsOfCC.remove("CSS")

//返回值是可选性,解包应用
if let skill = skillsOfCC.remove("OC") {
    print("OC is removed")
}

//集合移除所有元素操作
skillsOfCC.removeAll()

4、集合的数学应用

(1)并集

var skillsOfAAA:Set<String> = ["swift","OC","HTML"]
var skillsOfBBB:Set<String> = ["HTML","CSS","Javascript"]
var skillsOfCCC:Set<String> = ["swift","OC","CSS"]

//skillsOfAAA与skillsOfCCC并集
skillsOfAAA.union(skillsOfCCC)
skillsOfAAA

//skillsOfAAA与skillsOfCCC并集并且赋值给skillsOfAAA
skillsOfAAA.unionInPlace(skillsOfCCC)
skillsOfAAA

(2)交集

//交集、

skillsOfAAA.intersect(skillsOfCCC)
skillsOfAAA

skillsOfAAA.intersectInPlace(skillsOfCCC)
skillsOfAAA

(3)A有C没有

//A有C没有

skillsOfAAA.subtract(skillsOfCCC)
skillsOfAAA

skillsOfAAA.subtractInPlace(skillsOfCCC)
skillsOfAAA

(3)A+C减去AC共有的

//A+C减去AC共有的

skillsOfAAA.exclusiveOr(skillsOfCCC)
skillsOfAAA

skillsOfAAA.exclusiveOrInPlace(skillsOfCCC)
skillsOfAAA

集合不光可以与集合进行数学运算操作,也可以与数组进行数学操作运算

//集合可以与数组进行操作

skillsOfAAA.union(["OC","Java"])

var skillsOfD: Set = ["swift"]

(4)常用数学运算判断

//判断是否是子集
skillsOfD.isSubsetOf(skillsOfAAA)

//判断是否是真子集
skillsOfD.isStrictSubsetOf(skillsOfAAA)


//判断是否是父集
skillsOfD.isSupersetOf(skillsOfAAA)

//判断是否是真父集
skillsOfD.isStrictSupersetOf(skillsOfAAA)

//集合是否相离的

skillsOfD.isDisjointWith(skillsOfAAA)
<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

    swift集合