# 可选值的基本用法

URL: https://caijiao.org/swift/10-optionals/01-optionals
Source: docs/swift/10-optionals/01-optionals.md
Description: 本章介绍 Swift 中可选值的基本用法，帮助开发者安全处理可能缺失的值，避免运行时错误。

Swift 使用可选类型（Optional）表示变量可能有值也可能为 nil，防止空值引发错误。

## 定义可选值

在类型后加 `?` 表示可选：

```swift
var name: String? = "小明"
var age: Int? = nil
````

## 访问可选值

访问前需要解包（unwrap）：

### 1. 强制解包（不推荐，可能崩溃）

```swift
print(name!)  // 当 name 不为 nil 时安全，否则崩溃
```

### 2. 可选绑定（推荐）

使用 `if let` 判断并解包：

```swift
if let unwrappedName = name {
    print("名字是 \(unwrappedName)")
} else {
    print("名字为空")
}
```

### 3. 空合并运算符

提供默认值：

```swift
let displayName = name ?? "匿名"
print(displayName)
```

## 总结

可选值是 Swift 保障安全的重要特性，合理使用避免空值引发的崩溃。
