Skip to content

Instantly share code, notes, and snippets.

@ConfusedVorlon
Created January 24, 2020 11:20
Show Gist options
  • Save ConfusedVorlon/276bd7ac6c41a99ea0514a34ee9afc3d to your computer and use it in GitHub Desktop.
Save ConfusedVorlon/276bd7ac6c41a99ea0514a34ee9afc3d to your computer and use it in GitHub Desktop.
Add Codable support to @published
import Foundation
import SwiftUI
extension Published:Decodable where Value:Decodable {
public init(from decoder: Decoder) throws {
let decoded = try Value(from:decoder)
self = Published(initialValue:decoded)
}
}
extension Published:Encodable where Value:Decodable {
public func encode(to encoder: Encoder) throws {
let mirror = Mirror(reflecting: self)
if let valueChild = mirror.children.first(where: { $0.label == "value"
}) {
if let value = valueChild.value as? Encodable {
do {
try value.encode(to: encoder)
return
} catch let error {
assertionFailure("Failed encoding: \(self) - \(error)")
}
}
else {
assertionFailure("Decodable Value not decodable. Odd \(self)")
}
}
else {
assertionFailure("Mirror Mirror on the wall - why no value y'all : \(self)")
}
}
}
@jolonf
Copy link

jolonf commented Apr 9, 2023

An approach that is working instead of protocols is using enums:

class Parent {
  @Published var child: Child
}

enum Child: Codable { 
  case custom(_ child: CustomChild)
}

class CustomChild: Codable {
  var value: String
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment