# 15.Array,Set,Dictionary

## 三种集合类型：

* Array
  * 有序数据集合
* Set
  * 无序无重复数据集合
* Dictionary
  * 无序键值对集合

![Img](/files/-MJ_I95x7MmZJFKBO336)

> Swift 中的数组、集合和字典必须明确其中保存的键和值类型，这样就可以避免插入一个错误数据类型的值。同理，对于获取到的值你也可以放心，其数据类型是确定的。

## Set

> 注意 `Swift` 的 `Set` 类型被桥接到 `Foundation` 中的 `NSSet` 类。

### 集合类型的Hash

一个类型想要存储在`Set`中必须是可`Hash`的。该类型必须提供一个方法来计算它的`Hash`值。(`Hashable`协议)

`Swift` 的所有基本类型（比如 `String`、`Int`、`Double` 和 `Bool`）默认都是可哈希化的，可以作为集合值的类型或者字典键的类型。没有关联值的枚举成员值默认也是可哈希化的。

#### 语法

```swift
// 声明
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]

// 推断
var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]
```

## 集合操作

![Img](/files/-MJ_I960h_aqRNjakqZV)

```swift
let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]

oddDigits.union(evenDigits).sorted()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
oddDigits.intersection(evenDigits).sorted()
// []
oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
// [1, 9]
oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()
// [1, 2, 9]
```

![Img](/files/-MJ_I961rN4GI1lTMl9T)

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

houseAnimals.isSubset(of: farmAnimals)
// true
farmAnimals.isSuperset(of: houseAnimals)
// true
farmAnimals.isDisjoint(with: cityAnimals)
// true
```


---

# 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://ryukiedev.gitbook.io/wiki/swift/array-set-dictionary.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.
