Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does not conform to protocol Decodable / Codable

Tags:

swift

swift4

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.

like image 799
arakweker Avatar asked Mar 03 '18 17:03

arakweker


People also ask

Can a protocol conform to Codable?

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 .

What is Codable and Decodable?

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.

What is Codable used for?

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.

Can a class be Codable Swift?

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 .


1 Answers

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.

like image 126
rmaddy Avatar answered Sep 20 '22 20:09

rmaddy