MeWrite Docs

Swift: Unexpectedly found nil while unwrapping an Optional value

Swiftの強制アンラップエラーの解決方法

概要

Optional型の値を強制アンラップ(!)した際にnilだった場合に発生するランタイムエラーです。

エラーメッセージ

Fatal error: Unexpectedly found nil while unwrapping an Optional value

原因

  1. 強制アンラップ: !でnilを参照
  2. IBOutlet未接続: StoryboardのOutlet接続忘れ
  3. 初期化順序: 依存関係のある変数の初期化順序

解決策

1. if letを使用

1
2
3
4
5
if let name = optionalName {
    print("Hello, \(name)")
} else {
    print("Name is nil")
}

2. guard letを使用

1
2
3
4
guard let name = optionalName else {
    return
}
print("Hello, \(name)")

3. nil合体演算子

1
let name = optionalName ?? "Unknown"

4. Optional Chaining

1
let count = user?.profile?.posts?.count ?? 0

よくある間違い

  • 強制アンラップの乱用
  • IBOutletの接続確認を怠る

Swift の他のエラー

最終更新: 2025-12-09