Could not cast value of type 🍎 iOS

Swift: Could not cast value of type 'X' to 'Y'

A force cast (as!) failed because the object isn’t the expected type.

Seen on: iOS

Meaning

Often a storyboard view controller/cell whose Custom Class isn’t set, JSON decoded as a different type (NSNumber vs String), or a dequeued cell of another class.

Common causes

  • as! with the wrong type
  • Storyboard scene/cell Custom Class not set
  • JSON value of unexpected type
  • Wrong cell identifier → different cell class

⚡ Quick fix

  1. Use as? with a guard and log the actual type
  2. Set the Custom Class (and Module) in IB
  3. Use Codable with correct types

Detailed fix by platform

Swift

  1. swift
    guard let vc = storyboard?.instantiateViewController(withIdentifier: "Detail") as? DetailViewController else {
        assertionFailure("Detail scene has wrong class"); return
    }

How to diagnose

  1. Types — Actual vs expected in the message
  2. IB — Custom Class set?

🔧 Still not fixed?

Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.