create codeable struct in swift

To make a struct codable in Swift, you need to conform to the Codable protocol. This protocol combines the Encodable and Decodable protocols, which means the Codable struct can encode and decode itself.

Here is an example of a Person struct that conforms to the Codable protocol:

main.swift
struct Person: Codable {
    var firstName: String
    var lastName: String
    var age: Int
}
95 chars
6 lines

To encode this struct to JSON, you'll need to create a JSONEncoder and call its encode method:

main.swift
let person = Person(firstName: "John", lastName: "Doe", age: 30)
let encoder = JSONEncoder()
let encodedPerson = try encoder.encode(person)
140 chars
4 lines

To decode a JSON data to this struct, you'll need to create a JSONDecoder and call its decode method:

main.swift
let decoder = JSONDecoder()
let decodedPerson = try decoder.decode(Person.self, from: encodedPerson)
101 chars
3 lines

The Person.self parameter tells the decoder what type to decode the JSON data to.

gistlibby LogSnag