swift学习之集合(Set)

Set 集合
创建和初始化一个空集

var letters = Set<Character>()
letters.insert("a")
// letters now contains 1 value of type Character
letters = []
// letters is now an empty set, but is still of type Set<Character>

用数组字面值创建一个集合

var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]

访问和修改一个集合

print("I have \(favoriteGenres.count) favorite music genres.")
// Prints "I have 3 favorite music genres."

使用Boolean isEmpty属性作为检查count属性是否等于的快捷方式0:

if favoriteGenres.isEmpty {
    print("As far as music goes, I'm not picky.")
} else {
    print("I have particular music preferences.")
}
// Prints "I have particular music preferences."

将新项目添加到集合中

favoriteGenres.insert("Jazz")

从集合中移除一个项目,如果该项目是该集合的成员,则移除该项目,并返回移除的值,或者nil如果该集合不包含该项目,则返回该值。另外,一个集合中的所有项目都可以用它的removeAll()方法删除。

if let removedGenre = favoriteGenres.remove("Rock") {
    print("\(removedGenre)? I'm over it.")
} else {
    print("I never much cared for that.")
}

集合是否包含特定的项目

if favoriteGenres.contains("Funk") {
    print("I get up on the good foot.")
} else {
    print("It's too funky in here.")
}
// Prints "It's too funky in here."

遍历集合

for genre in favoriteGenres {
    print("\(genre)")
}

Swift的Set类型没有定义的顺序。要按特定顺序迭代集合的值,请使用sorted()方法

for genre in favoriteGenres.sorted() {
    print("\(genre)")
}

setVennDiagram_2x.png

使用该intersection(:)方法创建一个只有两个集合通用的值的新集合。
使用该symmetricDifference(
:)方法创建一个新的集合中的值,而不是两个。(a,b集合去掉共同部分)
使用该union(:)方法创建一个包含两个集合中所有值的新集合。
使用该subtracting(
:)方法创建一个新的集合,其值不在指定的集合中。(a集合去掉a和b集合的交集)

let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]
 
oddDigits.union(evenDigits).sorted()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
oddDigits.intersection(evenDigits).sorted()
// []
oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
// [1, 9]
oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()
// [1, 2, 9]

集合关系
使用“is equal”运算符(==)来确定两个集合是否包含所有相同的值。
使用该isSubset(of:)方法确定一个集合的所有值是否包含在指定的集合中。
使用该isSuperset(of:)方法来确定一个集合是否包含指定集合中的所有值。
使用isStrictSubset(of:)or isStrictSuperset(of:)方法来确定一个集合是一个子集还是一个超集,但不等于一个指定的集合。
使用该isDisjoint(with:)方法确定两个集合是否没有共同的值。

let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
let cityAnimals: Set = ["🐦", "🐭"]
houseAnimals.isSubset(of: farmAnimals)
// true
farmAnimals.isSuperset(of: houseAnimals)
// true
farmAnimals.isDisjoint(with: cityAnimals)
// true
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,923评论 18 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,284评论 25 708
  • 53.计算字符 在字符串中获取字符值的数量, 可以使用字符串字符属性中的计数属性: let unusualMena...
    无沣阅读 1,134评论 0 4
  • 看到经常有作者用毛笔作画,简单的黑白,简单的线条,却运用不同的画法,粗细相间,互相呼应,看似无章法可寻,却一笔一画...
    雪鲸呀阅读 319评论 4 8
  • 天低高楼云依树,日映平湖水泛漪。 湖有鸳鸯划清波,耳畔丝竹唤醉意。 雨沐周口寒露秋,远人反作故人游。 千里归乡今一...
    木兰sunnyxu阅读 146评论 0 1