# Set

## 1. 集合类型的hash值

集合类型的元素和字典类型的key必须提供计算hash值和比较相等性的方法。即实现`Swift`标准库的`Hashable`协议。

`Swift`的基本类型包括`String`,`Int`,`Double`等都实现了`Hashable`协议

```swift
public protocol Hashable : Equatable {
    var hashValue: Int { get }


    func hash(into hasher: inout Hasher)
}

```

## 2. 初始化，构造一个集合

```swift

// Set 没有简化的初始化版本
var set1 = Set<Character>()


//  使用数组字面值创建集合
var set2 : Set<Int> = [1,2,3]

```

## 3. 插入元素

`insert(newMember:)`插入新的元素

```swift
set1.insert(11)
```

## 4. 删除元素

`remove(member:)`删除某个元素；如果集合包含元素，则删除并返回，如果不包含则返回nil

`removeAll()` 删除所有元素

```swift
array1.remove(4)

array1.removeAll()
```

## 5.遍历集合

`for-in` 循环中遍历一个集合中的所有值

```swift
for value in array1 {

}

```

## 6. 集合操作

![](https://docs.swift.org/swift-book/_images/setVennDiagram_2x.png)

* 使用 `intersection(_:)` 方法根据两个集合的交集创建一个新的集合。
* 使用 `symmetricDifference(_:)` 方法根据两个集合不相交的值创建一个新的集合。
* 使用 `union(_:)` 方法根据两个集合的所有值创建一个新的集合。
* 使用 `subtracting(_:)` 方法根据不在另一个集合中的值创建一个新的集合
* 使用“是否相等”运算符（==）来判断两个集合包含的值是否全部相同。
* 使用 `isSubset(of:)` 方法来判断一个集合中的所有值是否也被包含在另外一个集合中。
* 使用 `isSuperset(of:)` 方法来判断一个集合是否包含另一个集合中所有的值。
* 使用 `isStrictSubset(of:)` 或者 `isStrictSuperset(of:)` 方法来判断一个集合是否是另外一个集合的子集合或者父集合并且两个集合并不相等。
* 使用 `isDisjoint(with:)` 方法来判断两个集合是否不含有相同的值（是否没有交集）


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gitbook.existorlive.cn/kai-fa-yu-yan-xue-xi/swift/4.-ji-he-lei-xing/3.set.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
