swift里的数据结构:集合
2017-03-24 本文已影响0人
需要药
集合:是无序的,无重复元素的数据集合,提供集合操作,快速查找
初始化方法
1>.var myset: Set<String> = ["swift"]
2>.var myset: Set<Int> = []-----声明一个空集合
3>.var myset = Set<Double>()----声明一个空集合
4>.var myset: Set = ["swift","object-c"]---类型在后面的集合中已给出:String
数组强转成集合:var myset = Set(["A","B"])
集合常用方法
.count:集合元素个数
.isEmpty:
.first
.contains
遍历集合
for set in myset{
print(set)
}
比较
let myset: Set = [1,2,3]
let mysetTwo: Set = [1,2,2,3,3]
myset == mysetTwo
集合操作
添加
myset.insert("addone")
删除
myset.remove("swift")
删除不存在的元素:不会报错,返回nil
if let laug = myset.remove("html"){
print("删除成功")
}
删除所有元素
myset.removeall
获取两个集合的并集
myset.union(mysetTwo) 相对应+
unionInplace 相当于+=
更多操作可看文档