# 08.Optional实质

## 底层实现

我们先看看`Swift`中`Optional`是怎么实现的把

```
public enum Optional<Wrapped> : _Reflectable, NilLiteralConvertible {
    case None
    case Some(Wrapped)
    /// Construct a `nil` instance.
    public init()
    /// Construct a non-`nil` instance that stores `some`.
    public init(_ some: Wrapped)
    /// If `self == nil`, returns `nil`.  Otherwise, returns `f(self!)`.
    @warn_unused_result
    public func map<U>(@noescape f: (Wrapped) throws -> U) rethrows -> U?
    /// Returns `nil` if `self` is `nil`, `f(self!)` otherwise.
    @warn_unused_result
    public func flatMap<U>(@noescape f: (Wrapped) throws -> U?) rethrows -> U?
    /// Create an instance initialized with `nil`.
    public init(nilLiteral: ())
}
```

很明显可以看出，它实际是一个枚举。 `.Some`的关联值就是我们解包出来的

## ? & ！

在我们对一个`Optional`的变量进行赋值的时候，我们实际上是将初始值放到`.Some`中，取值是则是从`.Some`中取出。

* `!`
  * 强制解包，告诉系统这个变量不为`nil` 且 `.Some`中一定有值
  * 如果为空则会崩溃
* `?`
  * 解包时会先判断是否为`nil`如果不为空则正常解包，否则会返回`nil`即默认初始值


---

# 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/optional-shi-zhi.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.
