Back-end · formation gratuite

Swift Training

Learn Swift to develop Apple applications

  • Intermédiaire
  • 12 chapitres
  • Exemples de code
  • 100 % gratuit
Commencer le cours

Introduction to Swift

Swift is a modern, safe, and high-performance programming language created by Apple in 2014. Swift is designed to replace Objective-C and offers clear syntax, type safety, and high performance. Swift is open-source and can be used to develop iOS, macOS, watchOS, tvOS applications, and even server applications.

🍎 What is Swift?

Swift is a compiled, multi-paradigm, and type-safe programming language. Swift combines the best features of modern languages with clear and expressive syntax.

💡 Why is Swift so popular?

  1. iOS/macOS Development - Official language for Apple applications
  2. Modern syntax - Clear and expressive code, easy to read and maintain
  3. Safety - Type-safe, automatic memory management, optionals
  4. Performance - Compiled, performance close to C
  5. Open-source - Active community development
  6. SwiftUI - Modern framework for creating user interfaces

🚀 Why learn Swift?

Swift offers many opportunities:

  • ✅ iOS Development - Create applications for iPhone and iPad
  • ✅ macOS Development - Native applications for Mac
  • ✅ High demand - Strong demand for Swift developers
  • ✅ High salary - Attractive salaries in the Apple ecosystem
  • ✅ SwiftUI - Modern and declarative framework
  • ✅ Active community - Abundant support and resources

📋 Prerequisites to learn Swift

To learn Swift effectively, it is recommended to have:

  • ✅ Mac or iPad - To develop with Xcode (recommended)
  • ✅ Basic concepts - Variables, conditions, loops
  • ✅ Xcode - Apple's official IDE (free)

💡 Important note: To develop with Swift, you need Xcode (free on the Mac App Store). You can also use Swift Playgrounds on iPad or online environments like Repl.it.

🎯 Swift Use Cases

Swift is used for:

  • iOS Applications - iPhone and iPad applications
  • macOS Applications - Native applications for Mac
  • watchOS - Applications for Apple Watch
  • tvOS - Applications for Apple TV
  • Server - Backend development with Vapor
  • Scripts - Automation on macOS

📝 Basic Syntax

Swift has a modern and clear syntax. Swift uses braces {} to define code blocks and is type-safe.

// Premier programme Swift
print("Bonjour, monde !")

// Variables
let nom = "NiangProgrammeur"
let age = 25

// String interpolation pour formater les chaînes
print("Je m'appelle \(nom) et j'ai \(age) ans")

// Opérations simples
let resultat = 10 + 5
print("10 + 5 = \(resultat)")

💡 Important points about Swift syntax:

  • Swift uses braces {} to define code blocks
  • Comments use // for a line, or /* */ for multiple lines
  • Swift is case-sensitive (uppercase/lowercase matters)
  • Statements generally end without semicolon (optional)
  • Swift uses type inference

🔍 Swift code example

Here is an example showing Swift's basic syntax:

// Définition d'une fonction
func calculerMoyenne(_ nombres: [Double]) -> Double {
    // Calcule la moyenne d'un tableau de nombres
    guard !nombres.isEmpty else {
        return 0
    }
    let somme = nombres.reduce(0, +)
    let moyenne = somme / Double(nombres.count)
    return moyenne
}

// Utilisation
let notes: [Double] = [15, 18, 12, 20, 16]
let moyenne = calculerMoyenne(notes)
print("La moyenne est : \(moyenne)")

🔤 Variables and Constants

In Swift, you use var for variables (mutable) and let for constants (immutable).

// Déclaration de variables et constantes
var nom = "Swift"              // String (chaîne de caractères) - variable
let age = 30                   // Int (entier) - constante
let prix = 19.99               // Double (nombre décimal) - constante
var estActif = true            // Bool (booléen) - variable
var valeurNulle: String? = nil // Optional (peut être nil)

// Affichage
print(nom)
print(age)
print(prix)
print(estActif)
print(valeurNulle ?? "nil")

// Réassignation (seulement pour var)
var variable = 10
print(type(of: variable))      // Int

variable = 20                   // OK car var
// age = 31                     // Erreur : let est immuable

// Noms de variables valides (camelCase)
let nomUtilisateur = "Bassirou"
let ageUtilisateur = 25
let _prive = "variable privée"
let CONSTANTE = 3.14159         // Convention pour les constantes

📌 Rules for variables:

  • Use var for mutable variables
  • Use let for constants (recommended)
  • Type can be explicit or inferred
  • Variable names are in camelCase

📊 Data Types

Swift offers several data types: Int, Double, String, Bool, Array, Dictionary, etc.

// Types de base
let texte: String = "Hello"           // String (chaîne de caractères)
let nombre: Int = 42                  // Int (entier)
let decimal: Double = 3.14            // Double (nombre décimal)
let booleen: Bool = true              // Bool (booléen)
let valeurNulle: String? = nil        // Optional (peut être nil)

// Collections (structures de données)
var liste: [Int] = [1, 2, 3, 4, 5]   // Array (tableau ordonné, modifiable)
let tuple = (1, 2, 3)                 // Tuple (liste ordonnée, immuable)
var dictionnaire: [String: Any] = ["nom": "Swift", "age": 30]  // Dictionary (paires clé-valeur)
var ensemble: Set<Int> = [1, 2, 3, 4]  // Set (ensemble unique, non ordonné)

// Vérifier le type
print(type(of: texte))                // String
print(type(of: nombre))               // Int
print(type(of: liste))                // Array<Int>
print(type(of: dictionnaire))        // Dictionary<String, Any>

// Conversion de types
let ageStr = String(25)               // Convertir en String
let ageInt = Int("25")                // Convertir en Int (Optional)
let prixDouble = Double("19.99")      // Convertir en Double (Optional)

📚 Swift Data Types:

  • Int, Int8, Int16, Int32, Int64 - Signed integers
  • UInt, UInt8, UInt16, UInt32, UInt64 - Unsigned integers
  • Float, Double - Decimal numbers (floating point)
  • String - Character strings
  • Bool - Booleans (true/false)
  • Array - Ordered arrays
  • Dictionary - Dictionaries (key-value pairs)
  • Set - Sets (unique values)
  • Optional - Optional types (can be nil)

🔢 Operators

Swift supports arithmetic, comparison, logical, and assignment operators.

// Opérateurs arithmétiques
let a = 10
let b = 3

print(a + b)    // Addition: 13
print(a - b)    // Soustraction: 7
print(a * b)    // Multiplication: 30
print(a / b)    // Division: 3.3333333333333335
print(a / b)    // Division entière: utiliser Int(a / b) pour 3
print(a % b)    // Modulo (reste): 1
print(pow(Double(a), Double(b)))  // Puissance: 1000.0

// Opérateurs de comparaison
print(a > b)    // true (supérieur à)
print(a < b)    // false (inférieur à)
print(a >= b)   // true (supérieur ou égal)
print(a <= b)   // false (inférieur ou égal)
print(a == b)   // false (égalité)
print(a != b)   // true (différent)

// Opérateurs logiques
let x = true
let y = false
print(x && y)   // false (ET logique)
print(x || y)   // true (OU logique)
print(!x)       // false (NON logique)

// Opérateurs d'assignation
var c = 5
c += 3          // Équivalent à c = c + 3 (c devient 8)
c -= 2          // Équivalent à c = c - 2 (c devient 6)
c *= 2          // Équivalent à c = c * 2 (c devient 12)
c /= 3          // Équivalent à c = c / 3 (c devient 4)

// Comparaison d'identité (===)
let liste1 = [1, 2, 3]
let liste2 = [1, 2, 3]
let liste3 = liste1

print(liste1 === liste2)    // false (objets différents)
print(liste1 === liste3)    // true (même référence)
print(liste1 == liste2)     // true (valeurs égales)

🔀 Control Structures

Swift uses if, if-else, switch for conditions.

// Structure if simple
let age = 20

if age >= 18 {
    print("Vous êtes majeur")
} else {
    print("Vous êtes mineur")
}

// Structure if/else if/else
let age2 = 15

if age2 >= 18 {
    print("Vous êtes majeur")
    print("Vous pouvez voter")
} else if age2 >= 13 {
    print("Vous êtes adolescent")
} else if age2 >= 6 {
    print("Vous êtes enfant")
} else {
    print("Vous êtes un bébé")
}

// Conditions multiples
let note = 85
let mention: String

if note >= 90 {
    mention = "Excellent"
} else if note >= 80 {
    mention = "Très bien"
} else if note >= 70 {
    mention = "Bien"
} else if note >= 60 {
    mention = "Assez bien"
} else {
    mention = "Insuffisant"
}

print("Votre mention : \(mention)")

// Opérateur ternaire (expression conditionnelle)
let age3 = 20
let statut = age3 >= 18 ? "Majeur" : "Mineur"
print(statut)

// Conditions avec &&/||
let age4 = 25
let permis = true

if age4 >= 18 && permis {
    print("Vous pouvez conduire")
} else {
    print("Vous ne pouvez pas conduire")
}

🔄 Loops

Swift offers for-in, while, and repeat-while for loops.

// Boucle for-in avec range
for i in 0..<5 {
    print(i)  // Affiche 0, 1, 2, 3, 4
}

// Range avec début et fin (fermé)
for i in 1...5 {
    print(i)  // Affiche 1, 2, 3, 4, 5
}

// Range avec pas (stride)
for i in stride(from: 0, to: 10, by: 2) {
    print(i)  // Affiche 0, 2, 4, 6, 8
}

// Boucle for-in avec tableau
let fruits = ["pomme", "banane", "orange"]
for fruit in fruits {
    print("J'aime les \(fruit)")
}

// Boucle for-in avec index (enumerated)
let fruits2 = ["pomme", "banane", "orange"]
for (index, fruit) in fruits2.enumerated() {
    print("\(index): \(fruit)")
}

// Boucle while
var compteur = 0
while compteur < 5 {
    print(compteur)
    compteur += 1
}

// Boucle while avec break
var compteur2 = 0
while true {
    print(compteur2)
    compteur2 += 1
    if compteur2 >= 5 {
        break  // Sortir de la boucle
    }
}

// continue (passer à l'itération suivante)
for i in 0..<10 {
    if i % 2 == 0 {  // Si i est pair
        continue     // Passer au suivant
    }
    print(i)         // Affiche seulement les impairs: 1, 3, 5, 7, 9
}

// repeat-while (équivalent do-while)
var compteur3 = 0
repeat {
    print(compteur3)
    compteur3 += 1
} while compteur3 < 5

⚙️ Functions

Functions in Swift are defined with func and can have named parameters.

// Fonction simple (sans paramètres)
func direBonjour() {
    print("Bonjour !")
}

direBonjour()  // Appel de la fonction

// Fonction avec paramètres
func saluer(_ nom: String) -> String {
    return "Bonjour, \(nom) !"
}

let message = saluer("Swift")
print(message)  // "Bonjour, Swift !"

// Fonction avec plusieurs paramètres
func additionner(_ a: Int, _ b: Int) -> Int {
    return a + b
}

let resultat = additionner(5, 3)
print(resultat)  // 8

// Fonction avec paramètres par défaut
func saluerPersonne(_ nom: String, message: String = "Bonjour") -> String {
    return "\(message), \(nom) !"
}

print(saluerPersonne("Bassirou"))              // "Bonjour, Bassirou !"
print(saluerPersonne("Bassirou", message: "Salut"))  // "Salut, Bassirou !"

// Fonction avec labels de paramètres
func creerPersonne(nom: String, age: Int, ville: String = "Dakar") -> String {
    return "\(nom), \(age) ans, habite à \(ville)"
}

print(creerPersonne(nom: "Bassirou", age: 25))
print(creerPersonne(nom: "Bassirou", age: 25, ville: "Thiès"))

// Fonction avec variadic parameters
func additionnerNombres(_ nombres: Int...) -> Int {
    return nombres.reduce(0, +)
}

print(additionnerNombres(1, 2, 3, 4, 5))  // 15

// Closure (fonction anonyme)
let carre: (Int) -> Int = { x in x * x }
print(carre(5))  // 25

// Utilisation de map() avec closure
let nombres = [1, 2, 3, 4, 5]
let carres = nombres.map { $0 * $0 }
print(carres)  // [1, 4, 9, 16, 25]

📋 Collections

Swift offers Array, Set, and Dictionary to store collections of data.

// ========== ARRAYS ==========
// Création de tableaux
var nombres: [Int] = [1, 2, 3, 4, 5]
var fruits: [String] = ["pomme", "banane", "orange"]
var listeMixte: [Any] = [1, "deux", 3.0, true]

// Accès aux éléments (index commence à 0)
print(fruits[0])        // "pomme" (premier élément)
print(fruits[fruits.count - 1])  // "orange" (dernier élément)

// Modification
fruits[1] = "mangue"    // Remplacer "banane" par "mangue"

// Méthodes des tableaux
fruits.append("kiwi")           // Ajouter à la fin
fruits.insert("ananas", at: 1)  // Insérer à l'index 1
if let index = fruits.firstIndex(of: "pomme") {
    fruits.remove(at: index)     // Supprimer un élément
}
fruits.pop()                    # Supprimer le dernier élément
fruits.pop(0)                   # Supprimer l'élément à l'index 0

# Autres méthodes utiles
print(len(fruits))              # Longueur de la liste
print(fruits.count("banane"))   # Compter les occurrences
fruits.sort()                   # Trier la liste
fruits.reverse()                # Inverser la liste

# Slicing (tranches)
nombres = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(nombres[2:5])     # [2, 3, 4] (de l'index 2 à 4)
print(nombres[:3])      # [0, 1, 2] (du début à l'index 2)
print(nombres[3:])      # [3, 4, 5, 6, 7, 8, 9] (de l'index 3 à la fin)
print(nombres[::2])     # [0, 2, 4, 6, 8] (tous les 2 éléments)

# ========== DICTIONNAIRES ==========
# Création de dictionnaires
personne = {
    "nom": "Bassirou",
    "age": 25,
    "ville": "Dakar"
}

# Accès aux valeurs
print(personne["nom"])          # "Bassirou"
print(personne.get("age"))      # 25 (méthode get() plus sûre)
print(personne.get("email", "Non renseigné"))  # Valeur par défaut

# Modification et ajout
personne["age"] = 26            # Modifier
personne["email"] = "bassirou@example.com"  # Ajouter

# Méthodes des dictionnaires
print(personne.keys())          # Toutes les clés
print(personne.values())        # Toutes les valeurs
print(personne.items())         # Toutes les paires clé-valeur

# Parcourir un dictionnaire
for cle, valeur in personne.items():
    print(f"{cle}: {valeur}")

# Supprimer
del personne["email"]           # Supprimer une clé
personne.pop("ville")           # Supprimer et retourner la valeur

📦 Object-Oriented Programming

Swift supports classes, structures, enumerations, and protocols for OOP.

# Importer un module complet
import math

print(math.sqrt(16))        # 4.0 (racine carrée)
print(math.pi)              # 3.141592653589793
print(math.cos(0))          # 1.0

# Importer avec un alias
import datetime as dt
maintenant = dt.datetime.now()
print(maintenant)

# Importer des fonctions spécifiques
from math import sqrt, pi
print(sqrt(25))             # 5.0
print(pi)                   # 3.141592653589793

# Importer tout d'un module (non recommandé)
from math import *
print(sin(0))               # 0.0

# Modules standards utiles
import random
print(random.randint(1, 100))  # Nombre aléatoire entre 1 et 100

import os
print(os.getcwd())          # Répertoire courant

import sys
print(sys.version)          # Version de swift

# Créer son propre module
# Créer un fichier mon_module.py avec :
# def ma_fonction():
#     return "Hello from module"
#
# Puis l'importer :
# import mon_module
# print(mon_module.ma_fonction())

🏗️ Protocols and Extensions

Protocols define contracts, and extensions allow adding functionality.

# Définir une classe
class Personne:
    # Constructeur (méthode spéciale __init__)
    def __init__(self, nom, age):
        self.nom = nom      # Attribut d'instance
        self.age = age
    
    # Méthode d'instance
    def se_presenter(self):
        return f"Je m'appelle {self.nom} et j'ai {self.age} ans"
    
    def avoir_ans(self, annees):
        self.age += annees
        return f"Dans {annees} ans, j'aurai {self.age} ans"

# Créer des objets (instances)
personne1 = Personne("Bassirou", 25)
personne2 = Personne("Aminata", 30)

# Utiliser les méthodes
print(personne1.se_presenter())
print(personne2.se_presenter())
print(personne1.avoir_ans(5))

# Accéder aux attributs
print(personne1.nom)
print(personne1.age)

# Classe avec attributs de classe
class Voiture:
    # Attribut de classe (partagé par toutes les instances)
    nombre_voitures = 0
    
    def __init__(self, marque, modele):
        self.marque = marque
        self.modele = modele
        Voiture.nombre_voitures += 1
    
    def __str__(self):
        return f"{self.marque} {self.modele}"

voiture1 = Voiture("Toyota", "Corolla")
voiture2 = Voiture("Honda", "Civic")
print(f"Nombre de voitures créées : {Voiture.nombre_voitures}")

# Héritage
class Etudiant(Personne):
    def __init__(self, nom, age, ecole):
        super().__init__(nom, age)  # Appeler le constructeur parent
        self.ecole = ecole
    
    def etudier(self):
        return f"{self.nom} étudie à {self.ecole}"

etudiant = Etudiant("Bassirou", 25, "UCAD")
print(etudiant.se_presenter())  # Méthode héritée
print(etudiant.etudier())       # Méthode spécifique

📁 Error Handling

Swift uses do-catch and try to handle errors safely.

# Écrire dans un fichier (mode 'w' = write)
with open("fichier.txt", "w", encoding="utf-8") as f:
    f.write("Bonjour swift !\n")
    f.write("Ceci est la deuxième ligne\n")

# Lire un fichier (mode 'r' = read)
with open("fichier.txt", "r", encoding="utf-8") as f:
    contenu = f.read()
    print(contenu)

# Lire ligne par ligne
with open("fichier.txt", "r", encoding="utf-8") as f:
    for ligne in f:
        print(ligne.strip())  # strip() enlève les sauts de ligne

# Lire toutes les lignes dans une liste
with open("fichier.txt", "r", encoding="utf-8") as f:
    lignes = f.readlines()
    print(lignes)

# Ajouter à un fichier (mode 'a' = append)
with open("fichier.txt", "a", encoding="utf-8") as f:
    f.write("Nouvelle ligne ajoutée\n")

# Modes de fichier
# 'r'  - Lecture (défaut)
# 'w'  - Écriture (écrase le fichier existant)
# 'a'  - Ajout (ajoute à la fin)
# 'x'  - Création exclusive (erreur si existe)
# 'b'  - Mode binaire (rb, wb)
# 't'  - Mode texte (défaut, rt, wt)
# '+'  - Lecture et écriture (r+, w+, a+)

# Gestion d'erreurs
try:
    with open("fichier_inexistant.txt", "r") as f:
        contenu = f.read()
except FileNotFoundError:
    print("Le fichier n'existe pas")
except PermissionError:
    print("Permission refusée")
except Exception as e:
    print(f"Erreur : {e}")

💡 Best practice: Use let for constants by default, and var only when you need to modify the value. Swift encourages immutability for safety.

🎓 Next Steps

Congratulations! You now have a solid foundation in Swift.

✅ What you have learned:

  • Swift syntax and variables
  • Data types (Int, Double, String, Bool)
  • Operators and control structures
  • Functions and closures
  • Collections (Array, Set, Dictionary)
  • Object-Oriented Programming
  • Protocols and extensions
  • Error handling

🚀 To go further:

  • SwiftUI - Modern framework for interfaces
  • Combine - Reactive programming
  • Core Data - Data persistence
  • Networking - API requests with URLSession
  • Concurrency - async/await for asynchronous programming
Cliquer pour discuter avec NiangProgrammeur
NiangProgrammeur
En ligne

Bonjour ! 👋

Comment puis-je vous aider aujourd'hui ?