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

1、代码

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、运行结果

定义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

相关推荐

  1. Swift学习笔记三节Set类型

    2023-12-28 03:08:02       48 阅读
  2. Swift学习笔记第二节:数组类型

    2023-12-28 03:08:02       53 阅读
  3. python三节:Str字符串类型(4)

    2023-12-28 03:08:02       59 阅读
  4. python三节:Str字符串类型(8)

    2023-12-28 03:08:02       54 阅读
  5. Swift 数据类型

    2023-12-28 03:08:02       24 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-28 03:08:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-28 03:08:02       101 阅读
  3. 在Django里面运行非项目文件

    2023-12-28 03:08:02       82 阅读
  4. Python语言-面向对象

    2023-12-28 03:08:02       91 阅读

热门阅读

  1. Torch 加速

    2023-12-28 03:08:02       49 阅读
  2. 路由的介绍

    2023-12-28 03:08:02       54 阅读
  3. CentOs7安装 Kafka

    2023-12-28 03:08:02       57 阅读
  4. 面向对象程序设计(泛型)

    2023-12-28 03:08:02       56 阅读
  5. 【vscode插件】之插件图标设置

    2023-12-28 03:08:02       66 阅读
  6. C/C++ const

    2023-12-28 03:08:02       62 阅读
  7. Linux Ubuntu安装nodejs

    2023-12-28 03:08:02       54 阅读