Why does @Published removes the codable protocol conformance

I have a simple class conforming to the codable protocol. Here is an example which is the same like in the developer documentation...


class Landmark: Codable {
    var name: String
    var foundingYear: Int
}


Because the two properties inside the class body are basic Swift types the compiler has nothing to complain.

But if I want to edit these properties using SwiftUI I must also make sure that the class conforms also to the ObservableObject protocol.


class Landmark: Codable, ObservableObject {
    @Published var name: String
    @Published var foundingYear: Int
}


Now I get an Xcode error message that type Landmark does not conform to the codable protocol anymore.


This is something I cannot understand. The property wrapper @Published should not change the type of the properties String and Int. The codable conformance should imho still be given to the class without additional lines of codes.

Look at detailed explanation here:


h ttps://www.hackingwithswift.com/books/ios-swiftui/adding-codable-conformance-for-published-properties


You have to declare Landmark as:


class Landmark: Codable, ObservableObject {

    enum CodingKeys: CodingKey {
        case name
        case foundingYear
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
        foundingYear = try container.decode(Int.self, forKey: .foundingYear)
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(name, forKey: .name)
        try container.encode(foundingYear, forKey: .foundingYear)
    }
  
    @Published var name: String = ""
    @Published var foundingYear: Int = 0
}

Does it work now ?, If so, don't forget to close the thread. You could also move it to SwiftUI section.


Good continuation.

I figured out a way to add Codable support to @Published<Value> where Value is Codable


it has a bit of a hack to access the value of the Published struct, but it seems to work


https://blog.hobbyistsoftware.com/2020/01/adding-codeable-to-published/

Reimplementing the Codable protocol works as well.

Why does @Published removes the codable protocol conformance
 
 
Q