lezione 07

codable e networking

decoding json e chiamate http.

livello: intermedio durata: 32 min output: api client badge: swift essentials

codable e json

struct Shot: Codable { let id: Int; let name: String }
let data = #"{\"id\":1,\"name\":\"A\"}"#.data(using: .utf8)!
let shot = try JSONDecoder().decode(Shot.self, from: data)

networking con urlsession

let url = URL(string: "https://example.com")!
let (data, _) = try await URLSession.shared.data(from: url)
print(data.count)

error handling

enum LoadError: Error { case missing }
func load(_ ok: Bool) throws -> String {
  if !ok { throw LoadError.missing }
  return "ok"
}

optional e guard

let city: String? = "Catania"
guard let city = city else { fatalError("no city") }
print(city)

esercizi

decodifica un json locale con Codable.

struct Item: Codable { let id: Int }
let data = #"{\"id\":1}"#.data(using: .utf8)!
let item = try JSONDecoder().decode(Item.self, from: data)
print(item.id)

panoramica

In questo capitolo su codable e networking lavoriamo su codable e json, networking con urlsession, error handling, optional e guard per creare micro-pattern riutilizzabili.

lavora in sequenza: leggi, prova, modifica gli snippet e annota i trade-off principali.

badge: swift essentials

obiettivi

  • capire e applicare codable e json in uno scenario reale
  • capire e applicare networking con urlsession in uno scenario reale
  • capire e applicare error handling in uno scenario reale
  • capire e applicare optional e guard in uno scenario reale

scheda rapida

struct Shot: Codable { let id: Int; let name: String }
let data = #"{\"id\":1,\"name\":\"A\"}"#.data(using: .utf8)!
let shot = try JSONDecoder().decode(Shot.self, from: data)

adatta questo scheletro agli esempi della lezione.

tips

  • preferisci value types quando possibile
  • usa guard per early exit
  • mantieni le view leggere
  • separa networking e ui
  • scrivi test su logica critica
  • gestisci i codici di risposta

tip: documenta ogni scelta architetturale.

mini progetto

crea un decoder JSON e validalo.

  • definisci Codable
  • decodifica
  • gestisci errori

output atteso: payload decodificato.

checklist

  • ho eseguito gli snippet e controllato l'output
  • ho annotato almeno 2 trade-off
  • ho completato il mini progetto
  • ho salvato un riepilogo personale
start a brief