Skip to content
Learni
View all tutorials
Swift

How to Get Started with Swift in 2026

Lire en français

Introduction

Swift is the modern, powerful programming language developed by Apple for iOS, macOS, watchOS, and tvOS. Launched in 2014, it blends C's safety and performance with modern scripting simplicity. In 2026, Swift 6 is the stable release, featuring concurrency improvements (actors) and better interoperability.

Why learn Swift? It's type-safe, handles errors without exceptions, and integrates seamlessly with Xcode for fast development. This beginner tutorial guides you step by step: from installation to advanced topics like optionals and classes. Every example is complete and functional, ready to copy into an Xcode Playground.

By the end, you'll create robust console programs ready for real apps. Allow 2-3 hours to master it all. Swift is approachable: no manual pointers, invisible garbage collection. Like an electric bike—smooth and safe right away.

Prerequisites

  • A Mac running macOS Ventura (13+) or later.
  • Xcode 16+ installed from the App Store (free, ~15 GB).
  • No prior experience needed, but basic programming knowledge helps.
  • Create a new Playground in Xcode: File > New > Playground.

First Program: Hello World

HelloWorld.playground
import Foundation

print("Bonjour, Swift en 2026 !")

let message = "Votre premier programme fonctionne."
print(message)

This code imports Foundation for core features, prints a greeting and a constant. Run it in an Xcode Playground (Cmd+R). Tip: Use Playgrounds for quick testing without full builds.

Variables and Constants

Swift differentiates variables (var, mutable) from constants (let, immutable). Type inference works automatically: let x = 42 becomes an Int. Default to let for better safety.

Variables, Constants, and Types

Variables.playground
import Foundation

// Constants (immutable)
let nom: String = "Alice"
let age: Int = 30
let salaire: Double = 45000.50
let actif: Bool = true

// Variables (mutable)
var score = 100
score += 50

print("Nom: \(nom), Âge: \(age), Nouveau score: \(score)")

// String interpolation
print("Salaire: \(salaire)€, Actif: \(actif ? "Oui" : "Non")")

Declares constants with explicit or inferred types, then modifies a variable. String interpolation with \() embeds values seamlessly. Stick to let by default: it prevents accidental mutations and bugs.

Control Flow: if, switch, Loops

If-else for conditions, switch for exhaustive matching (no fallthrough), for-in for iterations, while for loops. Switch handles multiple types without break statements.

Loops and Conditions

ControlFlow.playground
import Foundation

// If-else
let note = 16
if note >= 10 {
    print("Validé !")
} else if note >= 5 {
    print("Rattrapage.")
} else {
    print("Échec.")
}

// Exhaustive switch
let fruit = "pomme"
switch fruit {
case "pomme":
    print("Fruit rouge")
case "banane":
    print("Fruit jaune")
default:
    print("Autre")
}

// For-in
for i in 1...5 {
    print("Itération \(i)")
}

// While

var compteur = 0
while compteur < 3 {
    print("Compteur: \(compteur)")
    compteur += 1
}

Covers conditions, switch on strings, loops over ranges (1...5), and while loops. Switch requires exhaustive cases (use default). Pitfall: Missing default triggers a compile-time error—great for safety!

Functions and Parameters

Fonctions.playground
import Foundation

// Simple function
func saluer(_ nom: String) -> String {
    return "Bonjour, \(nom) !"
}

print(saluer("Bob"))

// Function with default parameters and inout
var experience = 5
func gagnerExperience(annees: Int = 1, experience: inout Int) {
    experience += annees
}
gagnerExperience(annees: 2, experience: &experience)
print("Expérience: \(experience)")

// Closure (anonymous function)
let calcul = { (a: Int, b: Int) -> Int in
    return a + b
}
print("Somme: \(calcul(3, 4))")

Defines functions with returns, default params, and inout (& for mutation). Closures act like lambdas. Minimize inout use to promote immutability.

Optionals: Handling Missing Values

Optionals (? ) represent nil. Avoid force unwrapping (!)—it's risky. Use if let, guard let, or ?? (nil coalescing) instead.

Optionals in Action

Optionals.playground
import Foundation

var emailOptionnel: String? = "user@example.com"

// Safe unwrapping with if let
if let email = emailOptionnel {
    print("Email: \(email)")
} else {
    print("Pas d'email")
}

// Guard let (early exit)
func traiterEmail(_ email: String?) {
    guard let e = email else {
        print("Erreur: email manquant")
        return
    }
    print("Traité: \(e)")
}
traiterEmail(emailOptionnel)

// Nil coalescing
let emailFinal = emailOptionnel ?? "default@example.com"
print("Final: \(emailFinal)")

emailOptionnel = nil

Handles optionals crash-free. Guard let cleans up functions with early exits. ?? provides defaults. Major pitfall: Force unwrap (!) crashes at runtime if nil—always use optional binding.

Structs and Classes

StructClass.playground
import Foundation

// Struct (value type, copied)
struct Personne {
    var nom: String
    let age: Int
    
    mutating func anniversaire() {
        // Requires mutating for var properties
    }
}

var alice = Personne(nom: "Alice", age: 30)

// Class (reference type, shared)
class Voiture {
    var marque: String
    
    init(marque: String) {
        self.marque = marque
    }
    
    func accelerer() {
        print("\(marque) accélère")
    }
}

let maVoiture = Voiture(marque: "Tesla")
maVoiture.accelerer()

let copie = maVoiture  // Shared reference
copie.marque = "BMW"
print(maVoiture.marque)  // BMW too!

Use structs for simple data (value-copying, thread-safe), classes for complex objects (reference-sharing). Classes need init. Structs require mutating for self-modifying methods. Prefer structs for most cases.

Best Practices

  • Prefer let over var: Immutability cuts bugs.
  • Always handle optionals with if/guard, never !.
  • Use structs for 90% of cases (fast, safe).
  • Adopt guard for early returns in functions.
  • Test in Playgrounds before full apps.

Common Errors to Avoid

  • Force unwrap (!) on nil optional → fatal crash.
  • Missing default in switch → compile error (good, but catches you off-guard).
  • Mixing struct/class: Structs copy, classes share → unexpected mutations.
  • Forgetting mutating in structs → compile error.

Next Steps

Master actors for Swift 6 concurrency, or build your first iOS app with SwiftUI. Check the official Swift documentation.

Explore our Learni iOS/Swift courses for certified training. Advance to SwiftUI next!

How to Get Started with Swift in 2026 | Tutorial | Learni