Swift 集合类型之集合

创建空集合

import UIKit

// 创建空集合
var letters = Set<Character>()
print("letters is of type Set<Character> with \(letters.count) items")

letters.insert("a")

letters = []

创建有元素的集合

// 创建有元素的集合
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]

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

// 集合空的判断
if favoriteGenres.isEmpty {
    print("As far as music goes, I'm not picky.")
} else {
    print("I have particular music preferences.")
}

单个集合的基本操作

// 集合插入元素
favoriteGenres.insert("Jazz")

// 集合移除元素
if let removeGenre = favoriteGenres.remove("Rock") {
    print("\(removeGenre)? 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.")
}

遍历集合

// 遍历集合
for genre in favoriteGenres {
    print("\(genre)")
}

print("排序之后输出")
for genre in favoriteGenres.sort() {
    print("\(genre)")
}

console log 如下:


屏幕快照 2016-08-03 下午7.39.32.png

多个集合的操作

// 集合的操作
let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]

// 两个集合的并集
let unionSet = oddDigits.union(evenDigits).sort()
print(unionSet)

// 两个集合的交集
let interSectSet = oddDigits.intersect(evenDigits).sort()
print(interSectSet)

// 在A集合里面但是不在B集合里面
let subtractingSet = oddDigits.subtract(singleDigitPrimeNumbers).sort()
print(subtractingSet)

console log 如下:


屏幕快照 2016-08-03 下午7.40.29.png

集合关系的操作

let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐏", "🐶", "🐱"]
let cityAnimals: Set = ["🐦", "🐭"]

// houseAnimals 是 farmAnimals 的子集
houseAnimals.isSubsetOf(farmAnimals)

// farmAnimals 是 houseAnimals 的父集
farmAnimals.isSupersetOf(houseAnimals)

// farmAnimals 和 cityAnimals 没有交集
farmAnimals.isDisjointWith(cityAnimals)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,286评论 19 139
  • 工厂模式类似于现实生活中的工厂可以产生大量相似的商品,去做同样的事情,实现同样的效果;这时候需要使用工厂模式。简单...
    舟渔行舟阅读 7,964评论 2 17
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,787评论 25 709
  • 2017年10月12日,秋高气爽,阳光明媚,高新区实验小学开展了2017年度的科技节活动。科技小制作展示、各种...
    颗儿阅读 558评论 0 0
  • 昨天可以说是我感觉幸福的一天,也是让我感觉特别痛苦的一天,真应了那句痛并快乐着。 最让我感动的三句话:给你带好吃的...
    凤笙_252g阅读 276评论 0 0