Chapter 16: Swift Data Types
1. The Big Picture – What Are Data Types in Swift?
A data type tells Swift:
- How much memory to reserve
- What kind of value is allowed
- What operations are possible on that value
Swift is a strongly typed language → the compiler checks types very strictly (much more than Python, JavaScript or PHP).
Swift has two major categories of types:
| Category | Examples | Created by you? | Main characteristic |
|---|---|---|---|
| Value types | Int, Double, Bool, String, Array, Dictionary, struct, enum | Yes (struct & enum) | Copied when assigned or passed (no shared memory) |
| Reference types | class, NSObject subclasses, closures (sometimes) | Yes (class) | Passed by reference (shared memory, like pointers in C/C++) |
Most everyday types you use at the beginning are value types.
2. The Most Common Built-in Data Types (you use these daily)
| Type | What it holds | Literal examples | Size / Notes | Default value if not set |
|---|---|---|---|---|
| Int | Whole numbers (positive, negative, zero) | 42, -5, 0, 1_000_000 | Usually 64-bit on 64-bit platforms | — |
| UInt | Only non-negative whole numbers | 0, 100, UInt.max | Rarely used directly | — |
| Double | Floating-point numbers (decimals) | 3.14, -0.001, 1.23e-4, 99.99 | 64-bit floating point (most common) | — |
| Float | Smaller floating-point numbers | 3.14 as Float | 32-bit — use only when memory is critical | — |
| Bool | true or false | true, false | 1 bit (but usually 1 byte) | — |
| String | Text (Unicode) | “Hello”, “నమస్తే”, “😺🚀” | Very powerful, immutable when let | — |
| Character | Single Unicode character | “A”, “₹”, “😊” as Character | Rarely used directly | — |
3. Examples – Try these right now
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
// Integers let age = 27 // Int let population = 1_420_000_000 // readable with underscores let negativeScore = -150 let veryLargeNumber = Int.max // maximum possible Int on this platform // Floating point let height = 1.72 // Double (most common choice) let price = 999.99 let verySmall = 1.23e-7 // scientific notation let temperature = 36.6 // Boolean let isLoggedIn = true let hasPremium = false let isRaining = false // String let name = "Sneha Reddy" let greeting = "నమస్తే, Hyderabad! 🌶️" let emojiOnly = "🔥🚀😺" // Single character (rare) let firstLetter : Character = "S" let rupeeSymbol : Character = "₹" |
4. Very Important: Type Inference vs Explicit Types
Swift almost always guesses the type correctly — this is called type inference.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Type inference (preferred 90–95% of the time) let count = 42 // Swift knows → Int let ratio = 0.618 // → Double let active = true // → Bool let message = "Hello" // → String // Explicit type (use when it improves clarity) let maxFileSizeBytes: Int64 = 10_000_000_000 let taxRate: Double = 0.18 let opacity: Float = 0.75 let userCount: UInt = 500 let grade: Character = "A" |
When to write the type explicitly?
- Working with very specific sizes (Int32, Int64, UInt8, Float…)
- Interacting with C / Objective-C APIs
- When the inferred type might be surprising
- In function parameters & return types (very common)
5. Real-life examples – how these types appear in actual apps
Example 1 – User profile
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
struct User { let id: UUID // unique identifier let username: String let age: Int let height: Double // meters let isPremium: Bool let bio: String? let rating: Float? // 4.85 / 5.0 } |
Example 2 – Shopping cart calculation
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
let itemPrice: Decimal = 1499.99 // better than Double for money! let quantity: Int = 3 let discountPercentage: Double = 15.0 let subtotal = itemPrice * Decimal(quantity) let discountAmount = subtotal * Decimal(discountPercentage / 100) let finalAmount = subtotal - discountAmount |
Note: Real apps usually use Decimal (not Double) for money!
Example 3 – Game state
|
0 1 2 3 4 5 6 7 8 9 10 11 |
var livesRemaining: Int = 5 var currentScore: Int = 0 var highScore: Int = 0 var playerX: Double = 0.0 var playerY: Double = 0.0 var isGameOver: Bool = false |
6. Common Beginner Traps & How to Avoid Them
| Trap / Mistake | Wrong / Dangerous Code | Correct / Safe Way | Why? |
|---|---|---|---|
| Using Float for most decimal numbers | let price: Float = 99.99 | let price: Double = 99.99 | Double is far more accurate |
| Using Double for money | let total: Double = 1234.56 + 0.01 | Use Decimal for currency | Floating point rounding errors |
| Assuming Int is always 32-bit | let huge = 5_000_000_000 | Use Int64 when needed | Int size depends on platform |
| Forgetting String is value type | Thinking let a = b shares memory | String is copied when assigned | No reference surprises |
| Using Character when String is enough | let letter: Character = “A” everywhere | Just use String in almost all cases | String is much more convenient |
7. Quick Reference – Most Used Types in Real Apps
| Situation | Recommended Type(s) | Example literal / value |
|---|---|---|
| Counting things, IDs, indices | Int | userCount = 1420 |
| Money, prices, calculations | Decimal | price = 999.99 |
| Measurements, coordinates | Double | latitude = 17.3850 |
| True/false flags | Bool | isDarkMode = true |
| Text, names, messages | String | username = “aarav_007” |
| Single letters / symbols | Character (rare) | currencySymbol = “₹” |
| Small counters / flags | UInt8, UInt16 (rare) | redValue: UInt8 = 255 |
| Very large / precise integers | Int64, UInt64 | fileSizeBytes: Int64 |
8. Small Practice – Choose the best type
Decide the most appropriate type for each:
|
0 1 2 3 4 5 6 7 8 9 10 11 |
let numberOfLikes = _________ // 1_245_678 let bodyTemperature = _________ // 36.6 °C let passwordCorrect = _________ // true/false let productPrice = _________ // 2499.99 INR let latitude = _________ // 17.385044 let maxUploadSizeMB = _________ // 50 (small number) |
Expected answers (common choices):
|
0 1 2 3 4 5 6 7 8 9 10 11 |
let numberOfLikes: Int = 1_245_678 let bodyTemperature: Double = 36.6 let passwordCorrect: Bool = true let productPrice: Decimal = 2499.99 let latitude: Double = 17.385044 let maxUploadSizeMB: UInt = 50 |
Would you like to continue with one of these next?
- Deep dive into String (very important)
- Number formatting when printing (%.2f, thousands separator…)
- Decimal vs Double – when & why
- Collections (Array, Dictionary, Set)
- Optionals (Int?, String?, nil)
- Or any other data type or topic you want
Just tell me — we’ll keep going in the same detailed, step-by-step, teacher-like style 😊
