<aside> 📌 목차

</aside>

What is Codable in Swift?

Codable is a protocol in Swift that allows for easy encoding and decoding of data.

By conforming to the Codable protocol, a type can be encoded to and decoded from various formats, such as JSON or Property List. Codable is particularly useful when working with data from web APIs, as it allows for easy serialization and deserialization of JSON data.

To conform to the Codable protocol, a type must specify how its properties should be encoded and decoded. This can be done by implementing the CodingKey protocol, which defines how each property should be represented in the encoded data.

Overall, Codable is a powerful and convenient tool for working with data in Swift, making it easier to serialize and deserialize data in a type-safe and customizable way.

To decode data using Codable, you can use the JSONDecoder class. Here's an example of decoding JSON data:

struct Person: Codable {
    let name: String
    let age: Int
}

let json = """
{
    "name": "John Smith",
    "age": 42
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
let person = try! decoder.decode(Person.self, from: json)

print(person.name) // Output: John Smith
print(person.age) // Output: 42

In this example, we define a Person struct that conforms to Codable. We then create a JSON string representing a Person object and convert it to a Data object. We then create a JSONDecoder instance and use it to decode the Data object into a Person object. Finally, we print out the name and age properties of the decoded Person object.

Here's an example of a simple JSON object:

Decoding 실패 케이스


<aside> 🚨 Decodable 객체 속성 타입은 기본적으로 Optional 로 정의하는게 바람직함