Swift Type Casting

Swift Introduction

🔁 Swift Type Casting (Complete & Easy Guide)

In Swift Type Casting means converting a value from one data type to another or checking the type of a value.

Swift is type-safe, so conversions must be explicit.


 Types of Type Casting in Swift

 type casting is mainly of two kinds:

  1. Type Conversion (Int ↔ Double, String ↔ Int, etc.)

  2. Type Casting with is, as, as?, as! (mainly for classes & protocols)


1️⃣ Type Conversion (Basic & Most Used)

 Int → Double

let a = 10
let b = Double(a)
print(b) // 10.0

 Double → Int (Decimal Lost ⚠️)

let x = 9.8
let y = Int(x)
print(y) // 9

 String → Int

let str = "25"
let num = Int(str)
print(num ?? 0)

✔ Returns Optional Int (Int?)


 Int → String

let age = 25
let ageStr = String(age)
print(ageStr)

 Double → String (Formatted)

let pi = 3.14159
print(String(format: "%.2f", pi))

2️⃣ Type Checking (is)

Used to check type at runtime.

let value: Any = 10

if value is Int {
print(“Value is Int”)
}


3️⃣ Type Casting (as, as?, as!)

as (Upcasting – Safe)

Used when casting to a superclass or protocol.

let num: Int = 10
let anyNum: Any = num // Upcasting

as? (Conditional Casting – Safe ✅)

Returns optional, avoids crash.

let value: Any = "Swift"

if let text = value as? String {
print(text)
}

✔ Recommended


as! (Forced Casting – Dangerous ⚠️)

Crashes if casting fails.

let value: Any = "Swift"
let text = value as! String
print(text)

❌ Avoid unless 100% sure


 Example with Classes (Real Use Case)

class Animal { }
class Dog: Animal { }
let pet: Animal = Dog()if let dog = pet as? Dog {
print(“This is a Dog”)
}


❌ Common Mistakes

❌ Implicit conversion:

let a = 10
let b = 2.5
// let sum = a + b ❌

✅ Correct:

let sum = Double(a) + b

🧠 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!

You may also like...