0Pricing
SwiftUI Academy · Aula

Decodificando JSON com Codable

Mapeie JSON para estruturas de modelo Swift.

Decodificando JSON com Codable é uma aula grátis de SwiftUI Academy no CoddyKit. Esta é a aula 1 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de SwiftUI Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de SwiftUI Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Why JSON Needs Decoding

APIs speak JSON, a text format Swift cannot use directly. You decode that text into real Swift types you can work with. 📦

Meet Codable

The Codable protocol lets a type convert itself to and from JSON automatically, so you rarely write parsing code by hand.

A Codable Struct

Just add Codable to your struct. Swift generates the encoding and decoding for every stored property for you.

struct User: Codable {
    let id: Int
    let name: String
}

Matching JSON Keys

Swift maps each property name straight to the matching JSON key. So "name" in JSON fills the name property exactly.

{ "id": 1, "name": "Ada" }

Decoding with JSONDecoder

A JSONDecoder turns raw Data into your type. You tell it which type to expect, and it does the rest.

let user = try JSONDecoder()
    .decode(User.self, from: data)

Working With Data

Network responses arrive as Data, a bag of bytes. The decoder reads those bytes and produces your typed value.

Decoding Arrays

To decode a JSON list, ask for an array of your type. One call gives you a ready-to-use Swift array. 🎉

let users = try JSONDecoder()
    .decode([User].self, from: data)

Renaming with CodingKeys

When JSON keys differ from your names, add CodingKeys to map a snake_case key onto a clean Swift property.

enum CodingKeys: String, CodingKey {
    case name = "full_name"
}

Optional Properties

Mark a property optional when the key may be missing. The decoder simply sets it to nil instead of throwing.

let avatar: String?

Decoding Can Throw

If the JSON shape does not match your type, decoding throws. Always wrap the call in try so you can handle bad data.

Nested Models

Nested JSON objects become nested structs. Make each level Codable and Swift decodes the whole tree at once.

struct Post: Codable {
    let author: User
}

Quick Check

Quick check on turning JSON into Swift types.

Recap: Codable

You learned that Codable plus JSONDecoder maps JSON into typed Swift values, with CodingKeys for renames and optionals for missing keys. 🙌

Perguntas Frequentes

A aula “Decodificando JSON com Codable” é grátis?

Sim — o texto completo de “Decodificando JSON com Codable” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de SwiftUI Academy, atualize para CoddyKit PRO. O curso de SwiftUI Academy inclui 4 aulas no total.

O que vou aprender em “Decodificando JSON com Codable”?

Mapeie JSON para estruturas de modelo Swift. Você pratica SwiftUI Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar SwiftUI Academy?

Nenhuma experiência prévia é necessária. SwiftUI Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 1 de 4.

Quanto tempo leva a aula “Decodificando JSON com Codable”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de SwiftUI Academy?

Sim. Cada aula de SwiftUI Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Decodificando JSON com Codable
  2. Chamando APIs com URLSession
  3. O Modificador .task
  4. Estados de Carregamento e Erro
← Voltar para SwiftUI Academy