この内容は古いバージョンです。最新バージョンを表示するには、戻るボタンを押してください。
バージョン:4
ページ更新者:guest
更新日時:2026-06-11 07:10:02

タイトル: エラー一覧
SEOタイトル: Swift よくあるエラー集と対処完全ガイド (Optional / Type / Codable)

この記事の要点
  • Cannot find xxx in scope — 識別子未定義 / import 漏れ / typo
  • Value of optional type must be unwrapped — Optional の安全な開封 (if let / guard / ??)
  • Type does not conform to protocol — 必須メソッド未実装
  • Cannot convert value of type — 型変換が必要 (Int(str) / as?)
  • Unexpectedly found nil while unwrapping — 強制アンラップ ! で nil 参照 → 即クラッシュ

Swift コンパイラエラーの特徴

Swift は型安全性が極めて厳格で、コンパイル時に多くのエラーを検出します。Optional (nil の表現)強い静的型付けがエラーの大半を占めます。Xcode のエラーメッセージは比較的わかりやすいですが、独特の用語に慣れが必要です。

1. Cannot find xxx in scope

error: cannot find 'UIButton' in scope
let button = UIButton()
             ^~~~~~~~

原因: 識別子が現在のスコープに存在しない。

  • import 漏れimport UIKit / import SwiftUI 忘れ
  • typoUIButtton のような綴りミス
  • アクセス修飾子privatefileprivate で外部から見えない
  • モジュール未追加 — Swift Package が project.pbxproj に未登録
// NG
let button = UIButton()  // import UIKit 漏れ

// OK
import UIKit
let button = UIButton()

2. Value of optional type must be unwrapped

error: value of optional type 'String?' must be unwrapped to a value of type 'String'
let len = name.count
          ^~~~
note: coalesce using '??' to provide a default
note: force-unwrap using '!' to abort execution if the optional value contains 'nil'

Swift の Optional は「値が無い可能性 (nil)」を型で表現する仕組み。String? のように ? が付いた型は、そのままだと中身を取り出せません。

var name: String? = "Alice"

// NG: そのままアクセスできない
// let len = name.count

// OK1: if let (Optional Binding)
if let unwrapped = name {
    print(unwrapped.count)
}

// OK2: guard let (早期 return)
func showLength(_ name: String?) {
    guard let unwrapped = name else { return }
    print(unwrapped.count)
}

// OK3: nil 合体演算子
let len = name?.count ?? 0

// OK4: Optional Chaining
let len2 = name?.count  // Int? を返す

// OK5: 強制アンラップ (非推奨、確実に値があるとき限定)
let len3 = name!.count  // nil ならクラッシュ

3. Type does not conform to protocol

error: type 'MyUser' does not conform to protocol 'Codable'
struct MyUser: Codable {
       ^~~~~~
note: cannot automatically synthesize 'Decodable' because '...' does not conform

原因: プロトコル必須メソッド / プロパティの未実装。Codable の場合、フィールドの型が Codable でない。

// NG: NSDate は Codable ではない (Date は Codable)
struct User: Codable {
    let name: String
    let createdAt: NSDate   // ← NSDate は Codable じゃない
}

// OK
struct User: Codable {
    let name: String
    let createdAt: Date     // ← Date は Codable
}

// カスタムキー名対応
struct User: Codable {
    let name: String
    let createdAt: Date

    enum CodingKeys: String, CodingKey {
        case name
        case createdAt = "created_at"  // JSON のキー名
    }
}

4. Cannot convert value of type

error: cannot convert value of type 'String' to expected argument type 'Int'
let n: Int = "42"
             ^~~~

Swift は暗黙の型変換を一切行いません。明示的に変換が必要:

// String → Int
let s = "42"
let n: Int? = Int(s)        // 失敗する可能性があるので Optional
let n2: Int = Int(s) ?? 0

// Int → String
let i = 42
let s2: String = String(i)
let s3: String = "\(i)"     // String 補間

// Double → Int
let d = 3.14
let i2: Int = Int(d)        // 切り捨て (3)

// 型キャスト (継承関係)
let view: UIView = UIButton()
if let button = view as? UIButton {
    button.setTitle("OK", for: .normal)
}

// 強制キャスト (失敗時クラッシュ)
let button2 = view as! UIButton

5. Unexpectedly found nil while unwrapping (実行時)

Fatal error: Unexpectedly found nil while implicitly unwrapping
an Optional value

原因: ! で強制アンラップした値が nil だった。@IBOutlet の接続忘れも典型。

// NG: 強制アンラップで nil 参照
let dict: [String: Int] = ["a": 1]
let value = dict["b"]!   // ← クラッシュ

// OK: 安全に
if let value = dict["b"] {
    print(value)
} else {
    print("missing")
}

// IBOutlet の接続忘れも要注意
class ViewController: UIViewController {
    @IBOutlet weak var label: UILabel!  // ← Storyboard で未接続なら nil

    override func viewDidLoad() {
        super.viewDidLoad()
        label.text = "Hello"  // ← nil クラッシュ
    }
}

6. Mutable property used in immutable context

error: cannot use mutating member on immutable value: 'point' is a 'let' constant
point.x = 10
struct Point {
    var x: Int
    var y: Int
    mutating func moveRight() { x += 1 }
}

let p = Point(x: 0, y: 0)
// p.x = 10            // ← NG: let は不変
// p.moveRight()       // ← NG: mutating は let で呼べない

var p2 = Point(x: 0, y: 0)
p2.x = 10              // ← OK
p2.moveRight()         // ← OK

7. async / await 関連

error: 'async' call in a function that does not support concurrency
let data = try await URLSession.shared.data(from: url)
// NG: 同期関数内で async 呼び出し
func loadData() {
    let data = try await URLSession.shared.data(from: url)  // ← NG
}

// OK1: async 関数にする
func loadData() async throws {
    let (data, _) = try await URLSession.shared.data(from: url)
}

// OK2: Task で包む
func loadData() {
    Task {
        let (data, _) = try await URLSession.shared.data(from: url)
        // ...
    }
}

8. SwiftUI State 管理

error: Generic struct 'Binding' requires that 'Int' conform to 'Hashable'

(または)

Modifying state during view update, this will cause undefined behavior.
// NG: View の body 内で State を変更
struct ContentView: View {
    @State var count = 0
    var body: some View {
        count += 1   // ← View 描画中に状態変更 → 警告
        return Text("\(count)")
    }
}

// OK: イベントハンドラで変更
struct ContentView: View {
    @State var count = 0
    var body: some View {
        VStack {
            Text("\(count)")
            Button("Increment") {
                count += 1   // ← OK
            }
        }
    }
}

9. Codable のキー不一致

Decoding error: keyNotFound(CodingKeys(stringValue: "createdAt"),
  context(codingPath: [], debugDescription: "No value associated with key"))
// JSON: { "created_at": "2026-01-01T00:00:00Z" }

// NG
struct User: Codable {
    let name: String
    let createdAt: Date   // ← JSON は created_at なので不一致
}

// OK1: CodingKeys を定義
struct User: Codable {
    let name: String
    let createdAt: Date

    enum CodingKeys: String, CodingKey {
        case name
        case createdAt = "created_at"
    }
}

// OK2: グローバルに snake_case → camelCase 変換
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.dateDecodingStrategy = .iso8601
let user = try decoder.decode(User.self, from: jsonData)

10. Closure capture とメモリリーク

// NG: self を強参照キャプチャ → 循環参照
class ViewController: UIViewController {
    var onTap: (() -> Void)?

    override func viewDidLoad() {
        super.viewDidLoad()
        onTap = {
            self.doSomething()  // ← self を強参照
        }
    }
}

// OK: [weak self] でキャプチャリスト
onTap = { [weak self] in
    self?.doSomething()
}

// OK: [unowned self] (self が必ず存在する場合)
onTap = { [unowned self] in
    self.doSomething()
}

FAQ

Q: Optional ?! の違いがわからない
A: ? は Optional 型を表す (nil の可能性あり)。! は Implicitly Unwrapped Optional (暗黙的に開封) または強制アンラップ演算子。安全のため ? + if let / guard let を基本に。

Q: Swift のエラーメッセージが長くて読めない
A: Xcode の Issue Navigator (左の警告マーク) で要約版が見られます。「Fix-it」ボタンが出る場合は自動修正可能。

Q: 強制アンラップ ! はいつ使っていい?
A: 「絶対に nil にならない」と論理的に保証できる場合のみ (たとえば @IBOutlet)。原則は guard let + fatalError で意図を明示するほうが安全。