I'm using the following struct:
struct Item : Codable {
var category:String
var birthDate:Date
var switch:Bool
var weightNew: [Weight]
var weightOld: Array<Double>
var createdAt:Date
var itemIdentifier:UUID
var completed:Bool
func saveItem() {
DataManager.save(self, with: itemIdentifier.uuidString)
}
func deleteItem() { DataManager.delete(itemIdentifier.uuidString)
}
mutating func markAsCompleted() {
self.completed = true
DataManager.save(self, with: itemIdentifier.uuidString)
}
}
And for weight:
struct Weight {
var day:Int
var weight:Double
var type:Bool
}
After changing weightOld to weightNew I get two errors: - Type 'Item' does not conform to protocol 'Decodable' - Type 'Item' does not conform to protocol 'Codable'
If I leave out 'var weightNew: [Weight]' it works. Don't know what is happening and how to solve it... Help is appreciated.
Codable is Encodable , but the compiler says it does not conform to it. This may sound strange, but it's because we are using Codable as a type, and the type Codable (not the protocol definition of Codable ) does not conform to Encodable .
typealias Codable = Decodable & Encodable. Decodable protocol Decodable : A type that can decode itself from an external representation (bytes to object) Encodable protocol Encodable : A type that can encode itself to an external representation. ( object to bytes) Codable = both encoding and decoding.
Codable allows you to insert an additional clarifying stage into the process of decoding data into a Swift object. This stage is the “parsed object,” whose properties and keys match up directly to the data, but whose types have been decoded into Swift objects.
Remember, Swift's String , Int , and Bool are all Codable ! Earlier I wrote that your structs, enums, and classes can conform to Codable . Swift can generate the code needed to extract data to populate a struct's properties from JSON data as long as all properties conform to Codable .
Everything needs to be Codable. So far your Weight
struct is not Codable. Update Weight
to be Codable as well and then Item
will be Codable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With