Cannot assign value of type '...' to type '...'
Cannot assign value of type '...' to type '...'
DodaTech
2 min read
The “Cannot assign value of type” error occurs when you try to assign a value of one type to a variable declared with a different type. Swift is a type-safe language and does not perform implicit type conversions.
What It Means
Swift enforces strict type checking at compile time. Every variable and expression has a known type, and assignments must match that type exactly. If you try to assign an Int to a String variable, or a Float to an Int variable, the compiler rejects the code with this error.
Why It Happens
- Numeric type mismatch — assigning an
Intto aDoublevariable or vice versa. - Missing explicit cast — a method returns
AnyorAnyObjectand you assign it to a typed variable. - Wrong type annotation — you declared a variable as
Stringbut the expression producesInt. - Optional vs non-optional mismatch — assigning
String?to aStringvariable. - Subclass/superclass mismatch — assigning a parent class instance to a child class variable.
- Literal type inference confusion —
5isInt,5.0isDoubleby default.
How to Fix It
1. Use explicit type conversion
let count: Int = 42
// ❌ Cannot assign Int to Double
let pi: Double = count
// ✅ Explicit conversion
let pi = Double(count)2. Fix optional vs non-optional assignments
let optionalName: String? = "John"
// ❌ Cannot assign String? to String
let name: String = optionalName
// ✅ Either unwrap or use a default
let name = optionalName ?? "Guest"3. Cast with as? or as! for Any types
let anyValue: Any = "Hello"
// ❌ Cannot assign Any to String
let text: String = anyValue
// ✅ Safe downcast
if let text = anyValue as? String {
print(text)
}4. Correct type annotations
// ❌ Literal "5" defaults to Int
let value: Float = 5
// ✅ Explicit Float literal
let value: Float = 5.0
// Or convert
let value = Float(5)Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro