Skip to Content
Course content

2: Anatomy of a Swift Program

Click on the "Edit" button in the top corner of the screen to edit your slide content.

When I see developers moving to Swift from Java or C#, the first thing they usually do is wrap their entire program in a class or a main() function. They've been trained to believe that the compiler will throw a tantrum if there isn't a formal "entry point" wrapping every single line of code. In those languages, that's a rule. In Swift, it's often an unnecessary hurdle.

The "Everything Needs a Wrapper" Trap

You might think you need to structure a simple script like this just to get it to run:

import Foundation

class Program {
    func run() {
        let greeting = "Hello, Swift!"
        print(greeting)
    }
}

let myProg = Program()
myProg.run()

Now, this isn't "wrong" in the sense that it won't compile, but it's overkill. You're building a house around a single chair. In Swift, specifically in top-level code (like in a main.swift file or a Playground), you can just... write the code. The compiler is smart enough to treat the top level of your file as the executable entry point.

The Actual Hierarchy of a Swift File

If you look at a professional Swift file, you'll notice a specific rhythm to the anatomy. It's less about following a rigid rulebook and more about a logical flow from "global" to "specific."

First, you have your Imports. I always put these at the very top. You're telling Swift, "Hey, I need tools from this other toolbox." For example, if you want to use Date or UUID, you need import Foundation. If you're building a UI, you'll see import SwiftUI.

Next, you'll often see Global Constants or Configuration. These are values that the entire file needs to know about, defined using let. I personally prefer keeping these near the top so I don't have to hunt through 200 lines of code to change a timeout value or an API key.

Then come the Type Definitions. This is where your structs, enums, and classes live. This is the "blueprint" section of your anatomy. You aren't actually *doing* anything yet; you're just describing what the data looks like.

Finally, you have the Execution Logic. This could be a function call, a loop, or a series of statements that actually trigger the behavior of your program. Here is a concrete example of how this actually looks in a real-world scenario—a simple fuel efficiency tracker:

import Foundation // 1. The Toolbox

let milesPerGallonThreshold = 25.0 // 2. Global Configuration

struct Vehicle { // 3. The Blueprint
    let model: String
    let mpg: Double
}

func evaluateEfficiency(for vehicle: Vehicle) { // 3. The Blueprint (Logic)
    if vehicle.mpg >= milesPerGallonThreshold {
        print("\(vehicle.model) is efficient!")
    } else {
        print("\(vehicle.model) is a gas guzzler.")
    }
}

// 4. The Execution
let myTruck = Vehicle(model: "Ford F-150", mpg: 18.5)
evaluateEfficiency(for: myTruck)

Notice that the evaluateEfficiency function is defined before it's called, but in Swift, this isn't actually a requirement. You could move that function call to the top of the file, and it would still work perfectly. Swift scans the file for declarations before it executes the top-level code. This gives you the freedom to organize your file based on what makes the most sense for a human to read, not what the compiler demands.




📋 Practical Task

Refactoring the Movie Library Skeleton

You've been handed a messy piece of code for a Movie Library app. The previous developer wrapped everything in an unnecessary LibraryManager class and put the imports in the middle of the file. This is making the code harder to read and maintain.

Your Task: Refactor the following code to follow the proper Swift anatomy:

  1. Move the import to the very top.
  2. Remove the LibraryManager class wrapper entirely.
  3. Move the minRating constant to the top-level global scope.
  4. Ensure the Movie struct and the checkRating function are defined clearly before the execution logic.
struct Movie {
    let title: String
    let rating: Double
}

class LibraryManager {
    let minRating = 7.0
    
    func checkRating(movie: Movie) {
        if movie.rating >= minRating {
            print("\(movie.title) is worth watching.")
        } else {
            print("\(movie.title) skip it.")
        }
    }
}

import Foundation

let manager = LibraryManager()
let movie1 = Movie(title: "Inception", rating: 8.8)
manager.checkRating(movie: movie1)
Rating
0 0

There are no comments for now.

to be the first to leave a comment.