Swift 5.X——Set集合

1.Set集合的定义

import UIKit

var a:Set = [1,2,3,4]
print(a)

var b:Set<String> = ["hello","world"]
print(b)

var c:Set<Int> = []
print(c)

2.Set集合的基本操作

import UIKit

var a:Set<String> = ["hello","world","swift"]
print(a.count)//3
a.insert("aaa")//末尾s插入元素
print(a)//["hello", "world", "aaa", "swift"]
print(a.contains("hello"))//true。查看是否包含某元素
a.remove("hello")//删除某元素
print(a)//["swift", "aaa", "world"]

3.Set集合的高级操作

import UIKit

var a:Set<String> = ["hello","world","swift"]
var b:Set<String> = ["hello","world","Object-C"]

print(a.union(b))//["hello", "swift", "world", "Object-C"]。g合并
print(a.intersection(b))//["world", "hello"]。返回相同的元素
print(a.symmetricDifference(b))//Object-C", "swift"]。返回不同的元素
print(a==b)//false。判断两个Set是否相等
var c = a.filter({(item)->Bool in
    if(item=="hello"||item=="swift"){
        return false
    }else{
        return true
    }
})
print(c)//["world"]。Set的过滤
for item in b{
    print(item)//Object-C hello world。Set的遍历
}

猜你喜欢

转载自www.cnblogs.com/yangyh26/p/11826365.html
今日推荐