Skip to content

Instantly share code, notes, and snippets.

@andresr-dev
Created March 31, 2023 19:45
Show Gist options
  • Select an option

  • Save andresr-dev/81550bb5e82799c12bb818f4fc73f1d8 to your computer and use it in GitHub Desktop.

Select an option

Save andresr-dev/81550bb5e82799c12bb818f4fc73f1d8 to your computer and use it in GitHub Desktop.
This is how to conform to the Codable protocol within a class in swift
import Foundation
final class User: ObservableObject, Codable {
enum CodingKeys: CodingKey {
case name
}
@Published var name = "Paul Hudson"
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment