Swift Data Types
📊 Swift Data Types
Swift is strongly typed and type-safe, which helps prevent errors.
Categories of Swift Data Types
Data types are mainly divided into:
-
Basic (Built-in) Data Types
-
Collection Data Types
-
Special Data Types
Let’s understand each clearly 👇
1️⃣ Basic Data Types
🔸 Int (Integer)
Stores whole numbers.
🔸 Double
Stores decimal numbers (more precise).
🔸 Float
Decimal numbers with less precision (rarely used).
🔸 String
Stores text.
🔸 Bool (Boolean)
Stores true or false.
2️⃣ Collection Data Types
🔸 Array
Stores ordered multiple values of the same type.
Access value:
🔸 Dictionary
Stores key–value pairs.
Access value:
🔸 Set
Stores unique values (unordered).
Result:
3️⃣ Special Data Types
🔸 Optional (?)
Used when a value may or may not exist.
Safe access:
⚠️ Very important concept in Swift
🔸 Tuple
Groups multiple values of different types.
🔸 Any
Can store any type of value.
❌ Not recommended for beginners
🔸 AnyObject
Used for class instances only.
Type Inference (Automatic Type Detection)
It automatically detects data types.
✔ Clean
✔ Less code
✔ Safe
Type Safety Example
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) |
