Courses/Swift/Variables and Data Types

    Lesson 2 • Beginner

    Variables and Data Types 📦

    Master Swift's type system — from basic types like Int, String, and Bool to powerful Optionals and collections like Arrays, Dictionaries, and Sets.

    What You'll Learn in This Lesson

    • • All core data types: Int, Double, Float, String, Bool, Character
    • • Type inference vs explicit type annotations
    • • Optionals: the safe way to handle missing values
    • • Collections: Arrays, Dictionaries, and Sets
    • • Optional binding with if let and guard let

    1️⃣ Core Data Types

    Swift provides a rich set of built-in types. Unlike languages like Python or JavaScript, Swift is statically typed — the compiler knows every variable's type at compile time. This catches bugs early and enables powerful code completion in Xcode.

    Try It: Data Types

    Explore Int, Double, String, Bool, and type inference

    Try it Yourself »
    JavaScript
    // Swift Data Types — Simulated in JavaScript
    console.log("=== Swift's Core Data Types ===");
    console.log();
    
    // Int — whole numbers
    let population = 8000000;
    console.log("let population: Int = " + population);
    console.log("  Type: Int (64-bit on modern systems)");
    console.log("  Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807");
    console.log();
    
    // Double & Float — decimal numbers
    let pi = 3.14159265358979;
    let approxPi = 3.14;
    console.log("let pi: Double = " + pi + "    // 15+ de
    ...

    2️⃣ Optionals — Swift's Safety Net

    Optionals are one of Swift's most important features. They represent a value that might be absent (nil). This solves the "billion dollar mistake" of null pointer exceptions found in other languages. Every Optional must be explicitly unwrapped before use.

    Try It: Optionals

    Learn if let, guard let, nil coalescing, and force unwrapping

    Try it Yourself »
    JavaScript
    // Swift Optionals — The Billion Dollar Feature
    console.log("=== What Are Optionals? ===");
    console.log();
    console.log("An Optional says: 'There IS a value, and it equals X'");
    console.log("               or 'There is NO value at all (nil)'");
    console.log();
    
    // Simulating optionals
    class Optional {
      constructor(value) { this.value = value; this.hasValue = value !== null && value !== undefined; }
      unwrap() {
        if (!this.hasValue) throw new Error("Fatal error: Unexpectedly found nil while unw
    ...

    3️⃣ Collections

    Swift provides three primary collection types: Arrays (ordered lists), Dictionaries (key-value pairs), and Sets (unique unordered values). All three are generic and type-safe.

    Try It: Collections

    Work with Arrays, Dictionaries, and Sets

    Try it Yourself »
    JavaScript
    // Swift Collections — Arrays, Dictionaries, Sets
    console.log("=== Arrays ===");
    let fruits = ["Apple", "Banana", "Cherry", "Date"];
    console.log("var fruits = " + JSON.stringify(fruits));
    console.log("fruits[0] = " + fruits[0]);
    console.log("fruits.count = " + fruits.length);
    
    fruits.push("Elderberry");
    console.log("fruits.append(\"Elderberry\") → " + JSON.stringify(fruits));
    console.log();
    
    // Array operations
    console.log("fruits.contains(\"Banana\") = " + fruits.includes("Banana"));
    console.lo
    ...

    ⚠️ Common Mistakes

    ⚠️
    Force unwrapping with ! — Using optionalValue! crashes your app if the value is nil. Always prefer if let or guard let.
    ⚠️
    Array out of bounds — Accessing array[10] on a 5-element array crashes. Use array.indices.contains(10) to check first.
    💡
    Pro Tip: Use let for collections you don't need to modify. A let array is immutable and performs better.

    📋 Quick Reference — Types & Optionals

    TypeExample
    Intlet age = 25
    Doublelet pi = 3.14159
    Stringlet name = "Alice"
    Boollet active = true
    Optionalvar name: String? = nil
    Array[1, 2, 3]
    Dictionary["key": "value"]
    SetSet(["a", "b", "c"])

    🎉 Lesson Complete!

    You've mastered Swift's type system and Optionals! Next, learn how to control the flow of your programs with conditionals and loops.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service