Swift Type Casting
🔁 Swift Type Casting (Complete & Easy Guide)
Swift is type-safe, so conversions must be explicit.
Types of Type Casting in Swift
type casting is mainly of two kinds:
-
Type Conversion (Int ↔ Double, String ↔ Int, etc.)
-
Type Casting with
is,as,as?,as!(mainly for classes & protocols)
1️⃣ Type Conversion (Basic & Most Used)
Int → Double
Double → Int (Decimal Lost ⚠️)
String → Int
✔ Returns Optional Int (Int?)
Int → String
Double → String (Formatted)
2️⃣ Type Checking (is)
Used to check type at runtime.
3️⃣ Type Casting (as, as?, as!)
as (Upcasting – Safe)
Used when casting to a superclass or protocol.
as? (Conditional Casting – Safe ✅)
Returns optional, avoids crash.
✔ Recommended
as! (Forced Casting – Dangerous ⚠️)
Crashes if casting fails.
❌ Avoid unless 100% sure
Example with Classes (Real Use Case)
❌ Common Mistakes
❌ Implicit conversion:
✅ Correct:
🧠 Summary Table
| Purpose | Method |
|---|---|
| Int → Double | Double(value) |
| Double → Int | Int(value) |
| String → Int | Int(string) |
| Type check | is |
| Safe cast | as? |
| Force cast | as! |
