Skip to content
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 Int to a Double variable or vice versa.
  • Missing explicit cast — a method returns Any or AnyObject and you assign it to a typed variable.
  • Wrong type annotation — you declared a variable as String but the expression produces Int.
  • Optional vs non-optional mismatch — assigning String? to a String variable.
  • Subclass/superclass mismatch — assigning a parent class instance to a child class variable.
  • Literal type inference confusion5 is Int, 5.0 is Double by 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)
Can I overload operators to convert between types automatically?
No — Swift intentionally avoids implicit conversions to prevent subtle bugs. You must always write explicit conversions with type initializers like Int(value) or Double(value).
Why does 5 / 2 return 2 in Swift?
Integer division truncates the decimal. Both 5 and 2 are Int, so the result is Int(2). Use 5.0 / 2 or Double(5) / 2 for a Double result.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro