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
相关推荐
星幻元宇VR7 小时前
公共安全实训展厅设备【人防知识学习系统】
科技·学习·安全
心中有国也有家10 小时前
AtomGit Flutter 鸿蒙客户端:情绪日记的时间线实现
学习·flutter·华为·harmonyos
百里香酚兰11 小时前
【python学习笔记】pyttsx3库疑似只播报一次语音
笔记·python·学习
恣逍信点11 小时前
《凌微经》助读:本体论根基——“无之自悖”与“形性一体”
人工智能·科技·学习·程序人生·生活·交友·哲学
chh56313 小时前
C++--string
java·开发语言·网络·c++·学习
chnyi6_ya13 小时前
论文阅读笔记:VideoWeaver — 面向智能体长视频生成的技能评估与进化
论文阅读·笔记·音视频
J_yyy13 小时前
基于Reactor的文件管理服务开发笔记
c++·笔记·reactor·多线程编程·muduo
浩瀚地学14 小时前
【Java基础复习】IO流(四)
java·开发语言·经验分享·笔记·学习
疯狂打码的少年14 小时前
【操作系统】板块总结 + 下期预告(软件工程)
笔记·软件工程
心中有国也有家14 小时前
AtomGit Flutter 鸿蒙客户端:一键记录情绪的极致体验
学习·flutter·华为·harmonyos