Swift Data Types

Swift Introduction

📊 Swift Data Types

In Swift Data Types defines what kind of value a variable or constant can store.

Swift is strongly typed and type-safe, which helps prevent errors.


 Categories of Swift Data Types

Data types are mainly divided into:

  1. Basic (Built-in) Data Types

  2. Collection Data Types

  3. Special Data Types

Let’s understand each clearly 👇


1️⃣ Basic Data Types

🔸 Int (Integer)

Stores whole numbers.

let age: Int = 25
let year = 2025

🔸 Double

Stores decimal numbers (more precise).

let price: Double = 99.99
let pi = 3.14159

🔸 Float

Decimal numbers with less precision (rarely used).

let temperature: Float = 36.6

🔸 String

Stores text.

let name: String = "Swift"
let city = "Delhi"

🔸 Bool (Boolean)

Stores true or false.

let isLoggedIn: Bool = true
let hasAccess = false

2️⃣ Collection Data Types

🔸 Array

Stores ordered multiple values of the same type.

let numbers: [Int] = [1, 2, 3, 4]
let fruits = ["Apple", "Banana", "Mango"]

Access value:

print(fruits[0]) // Apple

🔸 Dictionary

Stores key–value pairs.

let student: [String: Int] = [
"Math": 90,
"Science": 85
]

Access value:

print(student["Math"] ?? 0)

🔸 Set

Stores unique values (unordered).

let uniqueNumbers: Set<Int> = [1, 2, 3, 3, 2]

Result:

{1, 2, 3}

3️⃣ Special Data Types

🔸 Optional (?)

Used when a value may or may not exist.

var nickname: String? = "Sam"
nickname = nil

Safe access:

print(nickname ?? "No nickname")

⚠️ Very important concept in Swift


🔸 Tuple

Groups multiple values of different types.

let person = (name: "Sanjit", age: 25, country: "India")
print(person.name)

🔸 Any

Can store any type of value.

var value: Any = 10
value = "Swift"
value = true

❌ Not recommended for beginners


🔸 AnyObject

Used for class instances only.

var obj: AnyObject

 Type Inference (Automatic Type Detection)

It automatically detects data types.

let marks = 85 // Int
let rating = 4.5 // Double
let subject = "Math" // String

✔ Clean
✔ Less code
✔ Safe


 Type Safety Example

let score = 90
// score = "Ninety" ❌ Error

Swift does not allow type mismatch.


🧠 Summary Table

Data Type Example
Int 25
Double 99.99
Float 36.6
String "Swift"
Bool true
Array [1, 2, 3]
Dictionary ["A": 1]
Set {1, 2, 3}
Optional String?
Tuple (name, age)

You may also like...