Swift学习笔记第三节:Set类型

1、代码

swift 复制代码
import Foundation

var set1: Set<Int> = [1, 2, 3, 4, 3]
print("定义1: \(set1)")
var set2 = Set(1...4)
print("定义2: \(set2)")
print("长度: \(set2.count)")
print("是否为空: \(set2.isEmpty)")
set1.insert(99)
set1.update(with: 33)
print("插入: \(set1)")
let (isInsert,val) = set1.insert(3)
print("是否插入成功: \(isInsert), 插入的值: \(val)")
set1.remove(4)
print("删除: \(set1)")
set1.removeAll()
print("删除所有: \(set1)")

let set3 = Set(1...7)
let set4 = Set(4...9)
let set5 = Set(2...4)
print("交集: \(set3.intersection(set4))")
print("并集: \(set3.union(set4))")
print("差集: \(set3.subtracting(set4))")
print("补集: \(set3.symmetricDifference(set4))")
print("是不是子集: \(set5.isSubset(of: set3))")
print("是不是超集: \(set3.isSuperset(of: set5))")
print("随机数: \(set3.randomElement() ?? -1)")
print("排序: \(set5.sorted())")

for item in set5 {
    print("遍历: \(item)")
}

for (index,value) in set5.enumerated() {
    print("索引: \(index), 值: \(value)")
}

set5.forEach{ item in
    print("遍历: \(item)")
}

2、运行结果

bash 复制代码
定义1: [3, 1, 4, 2]
定义2: [4, 2, 1, 3]
长度: 4
是否为空: false
插入: [3, 33, 99, 1, 4, 2]
是否插入成功: false, 插入的值: 3
删除: [3, 33, 99, 1, 2]
删除所有: []
交集: [4, 5, 7, 6]
并集: [6, 3, 2, 4, 5, 1, 7, 8, 9]
差集: [1, 3, 2]
补集: [3, 2, 1, 8, 9]
是不是子集: true
是不是超集: true
随机数: 1
排序: [2, 3, 4]
遍历: 2
遍历: 4
遍历: 3
索引: 0, 值: 2
索引: 1, 值: 4
索引: 2, 值: 3
遍历: 2
遍历: 4
遍历: 3
相关推荐
xiaotao1311 小时前
02-机器学习基础: 监督学习——线性回归
学习·机器学习·线性回归
墨黎芜2 小时前
ArcGIS从入门到精通——地图符号、注记的初步使用
学习·arcgis·信息可视化
小李云雾2 小时前
FastAPI重要知识点---中间件(Middleware)
学习·程序人生·中间件·fastapi·middleware
.Cnn2 小时前
JavaScript 前端基础笔记(网页交互核心)
前端·javascript·笔记·交互
小夏子_riotous3 小时前
Docker学习路径——3、常用命令
linux·运维·服务器·学习·docker·容器·centos
STLearner3 小时前
WSDM 2026 | 时间序列(Time Series)论文总结【预测,表示学习,因果】
大数据·论文阅读·人工智能·深度学习·学习·机器学习·数据挖掘
redaijufeng3 小时前
网络爬虫学习:应用selenium获取Edge浏览器版本号,自动下载对应版本msedgedriver,确保Edge浏览器顺利打开。
爬虫·学习·selenium
九成宫3 小时前
IT项目管理期末复习——Chapter 10 项目沟通管理
笔记·项目管理·软件工程
腾科IT教育3 小时前
零基础快速上岸HCIP,高效学习思路分享
学习·华为认证·hcip·hcip考试·hcip认证
23471021273 小时前
4.14 学习笔记
笔记·python·学习